<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\Tools\Campaign\ChooseLocation;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
use App\Campaigns\PublishGate;
use App\Campaigns\Publishing\MetaPublisher;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\PublishedLocationReadback;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\AllowedAdAccount;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInException;
use App\Services\Meta\AdSetSpec;
use App\Services\Meta\Meta;
use App\Services\Platforms\LinkedInAdapter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Mockery;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class CrossPlatformDmaTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    public function test_meta_market_is_reverified_and_reaches_the_exact_geo_market_payload(): void
    {
        $this->seedVerifiedCountries();
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['key' => 'COMSCORE_MARKET:2002', 'name' => 'Los Angeles', 'type' => 'geo_market', 'country_code' => 'US'],
                ['key' => 'wrong', 'name' => 'Los Angeles', 'type' => 'city', 'country_code' => 'US'],
            ]]),
            'https://graph.facebook.com/v25.0/act_123/reachestimate*' => Http::response([
                'data' => ['users_lower_bound' => 100000, 'users_upper_bound' => 200000, 'estimate_ready' => true],
            ]),
        ]);

        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(), 'name' => 'Meta market',
            'platform' => 'meta', 'status' => 'draft', 'ad_account_id' => 'act_123',
            'locations' => ['countries' => ['US', 'GB']],
        ]);
        $discovery = app(LocationDiscovery::class);
        $results = $discovery->search('meta', 'dma', 'US', 'Los Angeles', 'act_123');
        $this->assertSame(['COMSCORE_MARKET:2002'], array_column($results, 'external_id'));

        $mapping = $discovery->select('meta', 'dma', 'US', 'Los Angeles', 'COMSCORE_MARKET:2002', 'act_123');
        app(TargetingSelections::class)->addPlatformDma($campaign, $mapping, 0);

        $this->assertSame([
            'countries' => ['GB'], 'geo_markets' => [['key' => 'COMSCORE_MARKET:2002']],
        ], app(TargetingSelections::class)->metaGeoLocations($campaign->fresh()));
        $spec = new AdSetSpec(
            adAccountId: 'act_123', campaignId: '456', name: 'Meta market',
            budgetMinorUnits: 500, optimizationGoal: 'LINK_CLICKS', pageId: '111',
            targeting: ['geo_locations' => app(TargetingSelections::class)->metaGeoLocations($campaign->fresh())],
        );
        $this->assertSame([['key' => 'COMSCORE_MARKET:2002']], $spec->targetingSpec()['geo_locations']['geo_markets']);
        $this->assertSame(['COMSCORE_MARKET:2002'], app(PublishedLocationReadback::class)
            ->normaliseMeta(['geo_markets' => [['key' => 'COMSCORE_MARKET:2002']]])['geo_markets']);
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'location_types=%5B%22geo_market%22%5D'));
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'reachestimate')
            && str_contains($request->url(), 'COMSCORE_MARKET%3A2002'));
    }

    public function test_meta_market_search_accepts_provider_names_with_parentheses_and_ampersands(): void
    {
        $this->seedVerifiedCountries();
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake(['https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [[
            'key' => 'COMSCORE_MARKET:999', 'name' => 'Tyler-Longview',
            'type' => 'geo_market', 'country_code' => 'US',
        ]]])]);

        $results = app(LocationDiscovery::class)->search(
            'meta', 'dma', 'US', 'Tyler-Longview(Lufkin & Nacogdoches), TX', 'act_123',
        );

        $this->assertSame(['COMSCORE_MARKET:999'], array_column($results, 'external_id'));
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'Tyler-Longview')
            && str_contains($request->url(), 'Nacogdoches'));
    }

    public function test_linkedin_dma_search_selects_only_a_counted_market_and_replaces_whole_us_in_the_payload(): void
    {
        $this->seedVerifiedCountries();
        AllowedAdAccount::factory()->linkedin('556447014')->create();
        config(['platforms.linkedin.token' => 'test-token', 'platforms.linkedin.version' => '202609']);
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'name' => 'LinkedIn market',
            'platform' => 'linkedin', 'status' => 'draft', 'ad_account_id' => '556447014',
            'locations' => ['countries' => ['US', 'DE']], 'budget' => 50,
            'objective' => 'WEBSITE_VISITS', 'landing_url' => 'https://example.com',
        ]);
        app(Workspace::class)->bindTo('linkedin-dma-chat');
        app(Workspace::class)->focusOn($campaign);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
                ['urn' => 'urn:li:geo:80000189', 'name' => 'DMA® 803 - Los Angeles, United States', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                ['urn' => 'urn:li:geo:90000049', 'name' => 'Los Angeles Metropolitan Area', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
            ]]),
            'https://api.linkedin.com/rest/audienceCounts*' => Http::response(['elements' => [['total' => 16000000, 'active' => 0]]]),
        ]);

        $this->assertTrue(app(Answers::class)->handles('linkedin_location'));
        $this->assertTrue(json_decode((string) app(ChooseLocation::class)->handle(new Request([])), true)['ok']);
        $scopeChoices = app(Choices::class)->drain();
        $this->assertSame(['whole', 'dma'], array_column($scopeChoices[0]['options'], 'value'));
        app(Workspace::class)->rememberChoices($scopeChoices);
        $this->assertTrue(app(Answers::class)->apply('location_scope', 'dma'));
        $searchChoices = app(Choices::class)->drain();
        $this->assertSame('location_search', $searchChoices[0]['field']);
        app(Workspace::class)->rememberChoices($searchChoices);
        $this->assertTrue(app(Answers::class)->apply('location_search', [
            'country_code' => 'US', 'kind' => 'dma', 'query' => 'Los Angeles',
        ]));
        $choices = app(Choices::class)->drain();
        $this->assertSame('linkedin_location', $choices[0]['field']);
        $this->assertCount(1, $choices[0]['options']);
        app(Workspace::class)->rememberChoices($choices);
        $this->assertTrue(app(Answers::class)->apply('linkedin_location', 'urn:li:geo:80000189'));
        $this->assertSame(['urn:li:geo:80000189'], app(TargetingSelections::class)->linkedinDmaUrns($campaign->fresh()));

        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('createCampaignGroup')->once()->andReturn('111');
        $linkedin->shouldReceive('createCampaign')->once()->withArgs(function (string $account, array $payload): bool {
            $locations = $payload['targetingCriteria']['include']['and'][0]['or']['urn:li:adTargetingFacet:locations'] ?? [];

            return $account === '556447014'
                && $locations === ['urn:li:geo:101282230', 'urn:li:geo:80000189'];
        })->andReturn('222');
        $this->app->instance(LinkedIn::class, $linkedin);
        $this->assertSame('222', app(LinkedInAdapter::class)->createCampaign($campaign->fresh()));
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'rest/audienceCounts')
            && str_contains($request->url(), 'urn%3Ali%3Ageo%3A80000189'));
    }

    public function test_linkedin_market_mapping_change_after_review_blocks_publication(): void
    {
        $this->seedVerifiedCountries();
        $location = Location::factory()->create([
            'type' => 'dma', 'name' => 'Los Angeles', 'country_code' => 'US', 'iso_code' => null,
            'source' => 'linkedin', 'source_key' => 'urn:li:geo:80000189',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'linkedin',
            'external_id' => 'urn:li:geo:80000189',
            'provider_name' => 'DMA® 803 - Los Angeles, United States',
            'status' => 'verified', 'verified_at' => now(),
        ]);
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(), 'name' => 'LinkedIn market approval',
            'platform' => 'linkedin', 'status' => 'draft', 'ad_account_id' => '556447014',
            'locations' => ['countries' => ['US']],
        ]);
        app(TargetingSelections::class)->addPlatformDma($campaign, $mapping);

        $gate = Mockery::mock(PublishGate::class);
        $gate->shouldReceive('check')->andReturn([]);
        $this->app->instance(PublishGate::class, $gate);
        $publisher = app(Publisher::class);
        $proposal = $publisher->propose($campaign->fresh(), 'tester');

        $this->assertSame('proposed', $proposal->state);
        $this->assertSame(['urn:li:geo:80000189'], $proposal->params['linkedin_targeting']['dma_urns']);

        $mapping->update(['external_id' => 'urn:li:geo:80000190']);
        $decision = $publisher->approve($proposal, 'tester');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('changed since review', $decision->reason);
        $this->assertSame('draft', $campaign->fresh()->status);
    }

    public function test_meta_market_without_an_account_estimate_is_not_saved(): void
    {
        $this->seedVerifiedCountries();
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['key' => 'COMSCORE_MARKET:2002', 'name' => 'Los Angeles', 'type' => 'geo_market', 'country_code' => 'US'],
            ]]),
            'https://graph.facebook.com/v25.0/act_123/reachestimate*' => Http::response([
                'data' => ['users_upper_bound' => 0, 'estimate_ready' => false],
            ]),
        ]);

        try {
            app(LocationDiscovery::class)->select('meta', 'dma', 'US', 'Los Angeles', 'COMSCORE_MARKET:2002', 'act_123');
            $this->fail('An unconfirmed market must not become a verified mapping.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('did not confirm', $exception->getMessage());
            $this->assertDatabaseCount('platform_locations', 11);
        }
    }

    public function test_meta_market_is_rechecked_before_any_campaign_creation(): void
    {
        $this->seedVerifiedCountries();
        $location = Location::factory()->create([
            'type' => 'dma', 'name' => 'Los Angeles', 'country_code' => 'US', 'iso_code' => null,
            'source' => 'meta', 'source_key' => 'COMSCORE_MARKET:2002',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'meta',
            'external_id' => 'COMSCORE_MARKET:2002', 'provider_name' => 'Los Angeles, US',
            'status' => 'verified', 'verified_at' => now(),
        ]);
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(), 'name' => 'Meta market refusal',
            'platform' => 'meta', 'status' => 'draft', 'ad_account_id' => 'act_123',
            'locations' => ['countries' => ['US']],
        ]);
        app(TargetingSelections::class)->addPlatformDma($campaign, $mapping, 0);

        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('marketAudienceEstimate')->once()->with('act_123', 'COMSCORE_MARKET:2002')
            ->andThrow(new RuntimeException('Market no longer available.'));
        $meta->shouldNotReceive('validateCampaign');
        $meta->shouldNotReceive('createCampaign');
        $this->app->instance(Meta::class, $meta);
        $created = [];

        try {
            app(MetaPublisher::class)->create($campaign->fresh(), 'tester', $created);
            $this->fail('A changed market must stop before provider creation.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('no longer available', $exception->getMessage());
            $this->assertSame([], $created);
        }
    }

    public function test_linkedin_dma_without_a_valid_audience_count_stops_before_provider_creation(): void
    {
        $this->seedVerifiedCountries();
        AllowedAdAccount::factory()->linkedin('556447014')->create();
        config(['platforms.linkedin.token' => 'test-token', 'platforms.linkedin.version' => '202609']);
        $location = Location::factory()->create([
            'type' => 'dma', 'name' => 'Los Angeles', 'country_code' => 'US', 'iso_code' => null,
            'source' => 'linkedin', 'source_key' => 'urn:li:geo:80000189',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'linkedin',
            'external_id' => 'urn:li:geo:80000189',
            'provider_name' => 'DMA® 803 - Los Angeles, United States',
            'status' => 'verified', 'verified_at' => now(),
        ]);
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(), 'name' => 'LinkedIn DMA refusal',
            'platform' => 'linkedin', 'status' => 'draft', 'ad_account_id' => '556447014',
            'locations' => ['countries' => ['US']], 'budget' => 50,
            'objective' => 'WEBSITE_VISITS', 'landing_url' => 'https://example.com',
        ]);
        app(TargetingSelections::class)->addPlatformDma($campaign, $mapping, 0);
        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldNotReceive('createCampaignGroup');
        $this->app->instance(LinkedIn::class, $linkedin);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/audienceCounts*' => Http::response([
            'message' => 'Invalid param', 'errorDetails' => ['inputErrors' => [['code' => 'PARAM_INVALID']]],
        ], 400)]);

        $this->expectException(LinkedInException::class);
        app(LinkedInAdapter::class)->createCampaign($campaign->fresh());
    }
}
