<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\PendingChanges;
use App\Campaigns\Targeting\PublishedLocationReadback;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use App\Services\GoogleAdsService;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request as ToolRequest;
use Mockery;
use RuntimeException;
use Tests\TestCase;

class PublishedLocationReadbackTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $platform): Campaign
    {
        return Campaign::create([
            'user_id' => User::factory()->create()->getKey(),
            'name' => 'Location readback',
            'platform' => $platform,
            'status' => 'draft',
            'ad_account_id' => $platform === 'meta' ? 'act_111' : '1234567890',
            'locations' => ['countries' => ['US']],
        ]);
    }

    private function publish(Campaign $campaign): Campaign
    {
        $campaign->update([
            'status' => 'published',
            'external_campaign_id' => '12345',
            'external_ids' => ['campaign_id' => '12345', 'adset_id' => '67890'],
        ]);
        $campaign->update(['published_state' => app(PendingChanges::class)->snapshot($campaign)]);

        return $campaign->fresh();
    }

    private function metaPlace(): PlatformLocation
    {
        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Springfield', 'iso_code' => null,
            'country_code' => 'US', 'source' => 'meta', 'source_key' => '2420605',
        ]);

        return PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'meta',
            'external_id' => '2420605', 'provider_name' => 'Springfield, Illinois, US',
        ]);
    }

    private function googleCountry(): void
    {
        $location = Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'google',
            'external_id' => 'geoTargetConstants/2840',
        ]);
        config([
            'services.google_ads.customer_id' => '1234567890',
            'services.google_ads.refresh_token' => 'test-refresh-token',
        ]);
    }

    public function test_meta_readback_matches_exact_city_key_and_detects_a_changed_key(): void
    {
        $campaign = $this->campaign('meta');
        app(TargetingSelections::class)->addCampaignLocation($campaign, $this->metaPlace());
        $campaign = $this->publish($campaign);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->twice()->with('12345')->andReturn('111');
        $meta->shouldReceive('adSets')->twice()->with('12345', 'act_111', true)->andReturn(
            [['id' => '67890', 'targeting' => ['geo_locations' => ['cities' => [['key' => '2420605', 'name' => 'Springfield']]]]]],
            [['id' => '67890', 'targeting' => ['geo_locations' => ['cities' => [['key' => '9999']]]]]],
        );
        $this->app->instance(Meta::class, $meta);

        $matching = app(PublishedLocationReadback::class)->inspect($campaign);
        $this->assertSame('matches', $matching['status']);
        $this->assertSame(['2420605'], $matching['actual']['cities']);

        $changed = app(PublishedLocationReadback::class)->inspect($campaign);
        $this->assertSame('drift', $changed['status']);
        $this->assertSame(['9999'], $changed['actual']['cities']);
    }

    public function test_published_location_snapshot_ignores_json_object_key_order(): void
    {
        $campaign = $this->campaign('meta');
        app(TargetingSelections::class)->addCampaignLocation($campaign, $this->metaPlace());
        $campaign = $this->publish($campaign);
        $state = $campaign->published_state;
        $state['locations'] = array_reverse($state['locations'], true);
        $state['targeting_locations'][0] = array_reverse($state['targeting_locations'][0], true);
        $campaign->update(['published_state' => $state]);

        $this->assertSame([], app(PendingChanges::class)->requiringRebuild($campaign->fresh()));
    }

    public function test_meta_readback_rejects_unknown_geo_controls(): void
    {
        $campaign = $this->publish($this->campaign('meta'));
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('111');
        $meta->shouldReceive('adSets')->once()->andReturn([
            ['id' => '67890', 'targeting' => ['geo_locations' => ['countries' => ['US'], 'custom_locations' => [['latitude' => 1]]]]],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('additional geographic controls');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_meta_readback_accepts_only_its_observed_default_location_presence(): void
    {
        $readback = app(PublishedLocationReadback::class);
        $normalised = $readback->normaliseMeta([
            'geo_markets' => [['key' => 'COMSCORE_MARKET:2002', 'name' => 'Los Angeles, CA', 'country' => 'US']],
            'location_types' => ['home', 'recent', 'frequently_in'],
        ]);

        $this->assertSame(['COMSCORE_MARKET:2002'], $normalised['geo_markets']);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('different location-presence setting');
        $readback->normaliseMeta([
            'geo_markets' => [['key' => 'COMSCORE_MARKET:2002']],
            'location_types' => ['home'],
        ]);
    }

    public function test_meta_readback_rejects_a_city_radius_even_when_its_key_matches(): void
    {
        $campaign = $this->campaign('meta');
        app(TargetingSelections::class)->addCampaignLocation($campaign, $this->metaPlace());
        $campaign = $this->publish($campaign);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('111');
        $meta->shouldReceive('adSets')->once()->andReturn([[
            'id' => '67890',
            'targeting' => ['geo_locations' => ['cities' => [[
                'key' => '2420605', 'radius' => 25, 'distance_unit' => 'mile',
            ]]]],
        ]]);
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('radius targeting');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_meta_readback_accepts_provider_default_distance_unit_without_a_radius(): void
    {
        $normalised = app(PublishedLocationReadback::class)->normaliseMeta([
            'cities' => [[
                'country' => 'US', 'distance_unit' => 'mile', 'key' => '2440704',
                'name' => 'Springfield', 'region' => 'Illinois', 'region_id' => '3856',
            ]],
            'location_types' => ['frequently_in', 'home', 'recent'],
        ]);

        $this->assertSame(['2440704'], $normalised['cities']);
    }

    public function test_imported_meta_geography_stops_before_provider_readback(): void
    {
        $campaign = $this->campaign('meta');
        $campaign->update(['locations' => [
            'countries' => ['US'],
            'meta_geo_locations' => ['countries' => ['US'], 'custom_locations' => [['latitude' => 1]]],
        ]]);
        $campaign = $this->publish($campaign);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldNotReceive('campaignAccountId');
        $meta->shouldNotReceive('adSets');
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Imported Meta geography');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_meta_readback_rejects_a_different_ad_set(): void
    {
        $campaign = $this->publish($this->campaign('meta'));
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('111');
        $meta->shouldReceive('adSets')->once()->andReturn([
            ['id' => '99999', 'targeting' => ['geo_locations' => ['countries' => ['US']]]],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('different ad sets');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_meta_readback_refuses_a_campaign_on_another_account(): void
    {
        $campaign = $this->publish($this->campaign('meta'));
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('222');
        $meta->shouldNotReceive('adSets');
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('different ad account');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_readback_stops_when_local_country_targeting_changed_after_publication(): void
    {
        $campaign = $this->publish($this->campaign('meta'));
        $campaign->update(['locations' => ['countries' => ['CA']]]);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldNotReceive('adSets');
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Local country targeting changed');
        app(PublishedLocationReadback::class)->inspect($campaign->fresh());
    }

    public function test_google_readback_compares_provider_criteria_and_reports_unreviewed_exclusions_as_drift(): void
    {
        $this->googleCountry();
        $campaign = $this->publish($this->campaign('google'));
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->twice()
            ->with(Mockery::type(GoogleAdsConnection::class), '12345', true, false, true)
            ->andReturn(
                [['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/2840', 'country_code' => 'US', 'target_type' => 'Country', 'name' => 'United States', 'negative' => false, 'status' => 'ENABLED']],
                [['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/2840', 'country_code' => 'US', 'target_type' => 'Country', 'name' => 'United States', 'negative' => true, 'status' => 'ENABLED']],
            );
        $this->app->instance(GoogleAdsService::class, $google);

        $this->assertSame('matches', app(PublishedLocationReadback::class)->inspect($campaign)['status']);

        $drift = app(PublishedLocationReadback::class)->inspect($campaign);
        $this->assertSame('drift', $drift['status']);
        $this->assertSame(['geoTargetConstants/2840'], $drift['actual']['excluded_geo_targets']);
    }

    public function test_imported_google_geography_stops_before_provider_readback(): void
    {
        $campaign = $this->campaign('google');
        $campaign->update(['locations' => [
            'countries' => ['US'],
            'google_location_criteria' => [['geo_target' => 'geoTargetConstants/2840', 'negative' => false]],
        ]]);
        $campaign = $this->publish($campaign);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldNotReceive('readCampaignLocationCriteria');
        $this->app->instance(GoogleAdsService::class, $google);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Imported Google geography');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_google_readback_confirms_a_city_replaced_its_whole_country_criterion(): void
    {
        $this->googleCountry();
        $campaign = $this->campaign('google');
        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Springfield', 'iso_code' => null,
            'country_code' => 'US', 'source' => 'google', 'source_key' => 'geoTargetConstants/123',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'google',
            'external_id' => 'geoTargetConstants/123', 'provider_name' => 'Springfield, Illinois, United States',
        ]);
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);
        $campaign = $this->publish($campaign);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->once()->andReturn([
            ['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/123', 'country_code' => 'US', 'target_type' => 'City', 'name' => 'Springfield, Illinois, United States', 'negative' => false, 'status' => 'ENABLED'],
        ]);
        $this->app->instance(GoogleAdsService::class, $google);

        $result = app(PublishedLocationReadback::class)->inspect($campaign);

        $this->assertSame('matches', $result['status']);
        $this->assertSame(['geoTargetConstants/123'], $result['expected']['geo_targets']);
    }

    public function test_google_readback_matches_a_reviewed_search_city_exclusion(): void
    {
        $this->googleCountry();
        $campaign = $this->campaign('google');
        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Chicago', 'iso_code' => null,
            'country_code' => 'US', 'source' => 'google', 'source_key' => 'geoTargetConstants/1023191',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'google',
            'external_id' => 'geoTargetConstants/1023191', 'provider_name' => 'Chicago, Illinois, US',
        ]);
        app(TargetingSelections::class)->addGoogleLocationExclusion($campaign, $mapping);
        $campaign = $this->publish($campaign);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->once()->andReturn([
            ['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/2840', 'target_type' => 'Country', 'negative' => false, 'status' => 'ENABLED'],
            ['criterion' => 'customers/1234567890/campaignCriteria/12345~2', 'geo_target' => 'geoTargetConstants/1023191', 'target_type' => 'City', 'negative' => true, 'status' => 'ENABLED'],
        ]);
        $this->app->instance(GoogleAdsService::class, $google);

        $result = app(PublishedLocationReadback::class)->inspect($campaign);

        $this->assertSame('matches', $result['status']);
        $this->assertSame(['geoTargetConstants/1023191'], $result['actual']['excluded_geo_targets']);
    }

    public function test_google_readback_matches_an_exact_dma_and_detects_a_different_market(): void
    {
        $this->googleCountry();
        $campaign = $this->campaign('google');
        $location = Location::factory()->create([
            'type' => 'dma', 'name' => 'New York, NY', 'iso_code' => null,
            'country_code' => 'US', 'source' => 'google', 'source_key' => 'geoTargetConstants/200501',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'google',
            'external_id' => 'geoTargetConstants/200501',
            'parent_external_id' => 'geoTargetConstants/2840',
            'provider_name' => 'New York, NY, United States',
        ]);
        app(TargetingSelections::class)->addGoogleDma($campaign, $mapping);
        $campaign = $this->publish($campaign);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->twice()->andReturn(
            [['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/200501', 'target_type' => 'DMA Region', 'negative' => false, 'status' => 'ENABLED']],
            [['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/200502', 'target_type' => 'DMA Region', 'negative' => false, 'status' => 'ENABLED']],
        );
        $this->app->instance(GoogleAdsService::class, $google);

        $this->assertSame('matches', app(PublishedLocationReadback::class)->inspect($campaign)['status']);
        $this->assertSame('drift', app(PublishedLocationReadback::class)->inspect($campaign)['status']);
    }

    public function test_google_readback_compares_an_enabled_radius_center_and_distance(): void
    {
        $this->googleCountry();
        $campaign = $this->campaign('google');
        app(TargetingSelections::class)->addGoogleRadius($campaign, 'US', 40.712776, -74.005974, 10, 'mi');
        $campaign = $this->publish($campaign);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->twice()->with(
            Mockery::type(GoogleAdsConnection::class), '12345', true, true, true,
        )->andReturn([]);
        $google->shouldReceive('readCampaignProximityCriteria')->twice()->andReturn(
            [['latitude' => 40.712776, 'longitude' => -74.005974, 'radius' => 10.0, 'radius_unit' => 'mi', 'negative' => false, 'status' => 'ENABLED']],
            [['latitude' => 40.712776, 'longitude' => -74.005974, 'radius' => 12.0, 'radius_unit' => 'mi', 'negative' => false, 'status' => 'ENABLED']],
        );
        $this->app->instance(GoogleAdsService::class, $google);

        $this->assertSame('matches', app(PublishedLocationReadback::class)->inspect($campaign)['status']);
        $this->assertSame('drift', app(PublishedLocationReadback::class)->inspect($campaign)['status']);
    }

    public function test_google_readback_rejects_a_changed_presence_preference(): void
    {
        $this->googleCountry();
        $campaign = $this->campaign('google');
        app(TargetingSelections::class)->setGooglePresenceMode($campaign, 'PRESENCE_OR_INTEREST');
        $campaign = $this->publish($campaign);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignGeoPresence')->once()->andReturn('PRESENCE');
        $google->shouldNotReceive('readCampaignLocationCriteria');
        $this->app->instance(GoogleAdsService::class, $google);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('location-presence setting differs');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    public function test_google_readback_refuses_a_paused_location_criterion(): void
    {
        $this->googleCountry();
        $campaign = $this->publish($this->campaign('google'));
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->once()->andReturn([
            ['criterion' => 'customers/1234567890/campaignCriteria/12345~1', 'geo_target' => 'geoTargetConstants/2840', 'country_code' => 'US', 'target_type' => 'Country', 'name' => 'United States', 'negative' => false, 'status' => 'PAUSED'],
        ]);
        $this->app->instance(GoogleAdsService::class, $google);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('paused');
        app(PublishedLocationReadback::class)->inspect($campaign);
    }

    /**
     * The readback follows the campaign's account rather than refusing it.
     *
     * This asserted the opposite: a campaign whose account was not the
     * configured one was refused with "This campaign belongs to a different
     * Google Ads customer", before any request. That was safe while the allow
     * list permitted a single account, and became a contradiction once the flow
     * started asking which of the manager's children to buy on - it refused the
     * answer to its own question.
     *
     * The account is still gated, by the allow list inside CallLogger, which is
     * the check that is actually about permission.
     */
    public function test_google_readback_reads_the_campaigns_own_customer(): void
    {
        $this->googleCountry();
        $campaign = $this->publish($this->campaign('google'));
        $campaign->update(['ad_account_id' => '9999999999']);

        $connections = [];
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')
            ->once()
            ->andReturnUsing(function (GoogleAdsConnection $connection) use (&$connections): array {
                $connections[] = $connection->customer_id;

                return [[
                    'criterion' => 'customers/9999999999/campaignCriteria/12345~1',
                    'geo_target' => 'geoTargetConstants/2840',
                    'country_code' => 'US',
                    'target_type' => 'Country',
                    'name' => 'United States',
                    'negative' => false,
                    'status' => 'ENABLED',
                ]];
            });
        $this->app->instance(GoogleAdsService::class, $google);

        app(PublishedLocationReadback::class)->inspect($campaign->fresh());

        $this->assertSame(['9999999999'], $connections, 'the readback used the configured account, not the campaign\'s');
    }

    public function test_main_chat_exposes_a_read_only_published_location_review(): void
    {
        $campaign = $this->publish($this->campaign('meta'));
        $this->actingAs($campaign->user);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('111');
        $meta->shouldReceive('adSets')->once()->andReturn([
            ['id' => '67890', 'targeting' => ['geo_locations' => ['countries' => ['US']]]],
        ]);
        $this->app->instance(Meta::class, $meta);
        $workspace = app(Workspace::class);
        $workspace->bindTo('location-review-chat');
        $workspace->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__review_published_location');
        $this->assertNotNull($tool);

        $result = json_decode((string) $tool->handle(new ToolRequest([])), true);

        $this->assertTrue($result['ok']);
        $this->assertSame('matches', $result['status']);
        $this->assertSame(['US'], $result['actual']['countries']);
    }

    public function test_main_chat_cannot_read_another_users_published_location(): void
    {
        $campaign = $this->publish($this->campaign('meta'));
        $this->actingAs(User::factory()->create());
        $meta = Mockery::mock(Meta::class);
        $meta->shouldNotReceive('adSets');
        $this->app->instance(Meta::class, $meta);
        $workspace = app(Workspace::class);
        $workspace->bindTo('other-user-location-review');
        $workspace->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__review_published_location');

        $result = json_decode((string) $tool->handle(new ToolRequest([])), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('signed-in user', $result['error']);
    }
}
