<?php

namespace Tests\Feature;

use App\Agent\Tools\Campaign\ApplyPublishedLocationChange;
use App\Agent\Workspace;
use App\Campaigns\PendingChanges;
use App\Campaigns\Targeting\PublishedLocationChangePlanner;
use App\Campaigns\Targeting\PublishedLocationLocalCommitter;
use App\Campaigns\Targeting\PublishedLocationReadback;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\TargetingSet;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Mockery;
use RuntimeException;
use Tests\TestCase;

class PublishedLocationLocalCommitterTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $platform, bool $selected = false): array
    {
        foreach (['US', 'GB'] as $code) {
            $country = Location::factory()->create(['type' => 'country', 'iso_code' => $code, 'country_code' => $code]);

            if ($platform === 'google') {
                PlatformLocation::factory()->create([
                    'location_id' => $country->getKey(), 'platform' => 'google',
                    'external_id' => $code === 'US' ? 'geoTargetConstants/2840' : 'geoTargetConstants/2826',
                ]);
            }
        }

        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Springfield', 'country_code' => 'US',
            'iso_code' => null, 'source' => $platform, 'source_key' => 'springfield-'.$platform,
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => $platform,
            'external_id' => $platform === 'meta' ? '2440704' : 'geoTargetConstants/1016864',
            'provider_name' => 'Springfield, Illinois, US',
        ]);
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(),
            'name' => 'Published place edit', 'platform' => $platform, 'status' => 'draft',
            'ad_account_id' => $platform === 'meta' ? 'act_111' : '1234567890',
            'budget' => 20, 'locations' => ['countries' => ['US', 'GB']],
        ]);

        if ($selected) {
            app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);
        }

        $campaign->update(['status' => 'published', 'external_campaign_id' => '12345']);
        $campaign->unsetRelation('targetingSet');
        $state = app(PendingChanges::class)->snapshot($campaign);
        $state['budget'] = '10';
        $campaign->update(['published_state' => $state]);

        return [$campaign->fresh(), $mapping];
    }

    private function plan(Campaign $campaign, PlatformLocation $mapping, string $operation, array $before, ?int $replacedMappingId = null): array
    {
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->once()->andReturn([
            'status' => 'matches', 'platform' => $campaign->platform,
            'expected' => $before, 'actual' => $before,
        ]);
        $this->app->instance(PublishedLocationReadback::class, $readback);

        return app(PublishedLocationChangePlanner::class)->preview(
            $campaign, $operation, $mapping->getKey(),
            (int) ($campaign->targetingSet()->value('revision') ?? 0), $replacedMappingId,
        );
    }

    public function test_confirmed_meta_add_saves_city_and_only_location_baseline(): void
    {
        [$campaign, $mapping] = $this->campaign('meta');
        $plan = $this->plan($campaign, $mapping, 'add', [
            'countries' => ['GB', 'US'], 'cities' => [], 'regions' => [],
        ]);

        $saved = app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);

        $this->assertSame(1, $saved->targetingSet->revision);
        $this->assertSame('override', $saved->targetingSet->options['place_intent_mode']);
        $this->assertSame(['US', 'GB'], app(TargetingSelections::class)->countries($saved));
        $this->assertSame('2440704', $saved->published_state['targeting_locations'][0]['external_id']);
        $this->assertSame('10', $saved->published_state['budget']);
        $this->assertSame(['US', 'GB'], $saved->published_state['locations']['countries']);
    }

    public function test_confirmed_google_removal_restores_country_without_touching_budget_baseline(): void
    {
        [$campaign, $mapping] = $this->campaign('google', selected: true);
        $plan = $this->plan($campaign, $mapping, 'remove', [
            'geo_targets' => ['geoTargetConstants/1016864', 'geoTargetConstants/2826'],
        ]);

        $saved = app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);

        $this->assertSame(2, $saved->targetingSet->revision);
        $this->assertSame([], $saved->published_state['targeting_locations']);
        $this->assertSame('10', $saved->published_state['budget']);
        $this->assertSame(0, $saved->targetingSet->locations()->where('kind', 'city')->count());
    }

    public function test_confirmed_replacement_saves_only_the_new_city_without_broadening_country(): void
    {
        [$campaign, $old] = $this->campaign('meta', selected: true);
        $newLocation = Location::factory()->create([
            'type' => 'city', 'name' => 'Chicago', 'country_code' => 'US',
            'iso_code' => null, 'source' => 'meta', 'source_key' => 'chicago-meta',
        ]);
        $new = PlatformLocation::factory()->create([
            'location_id' => $newLocation->getKey(), 'platform' => 'meta',
            'external_id' => '2420605', 'provider_name' => 'Chicago, Illinois, US',
        ]);
        $plan = $this->plan($campaign, $new, 'replace', [
            'countries' => ['GB'], 'cities' => ['2440704'], 'regions' => [],
        ], $old->getKey());

        $saved = app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);

        $this->assertSame(2, $saved->targetingSet->revision);
        $this->assertSame([$new->getKey()], $saved->targetingSet->locations()->where('kind', 'city')->pluck('platform_location_id')->all());
        $this->assertSame('2420605', $saved->published_state['targeting_locations'][0]['external_id']);
        $this->assertSame(['US', 'GB'], app(TargetingSelections::class)->countries($saved));
        $this->assertSame('10', $saved->published_state['budget']);
    }

    public function test_inherited_country_override_discards_stale_country_rows(): void
    {
        [$campaign, $mapping] = $this->campaign('meta');
        $brief = Brief::factory()->create([
            'user_id' => $campaign->user_id,
            'locations' => ['countries' => ['US']],
        ]);
        $campaign->update(['brief_id' => $brief->getKey(), 'locations' => ['countries' => ['US']]]);
        $set = TargetingSet::query()->create([
            'campaign_id' => $campaign->getKey(), 'platform' => 'meta',
            'mode' => 'inherit', 'revision' => 1, 'schema_version' => 1,
        ]);
        $staleCountry = Location::query()->where('iso_code', 'GB')->firstOrFail();
        $set->locations()->create([
            'location_id' => $staleCountry->getKey(), 'operation' => 'include',
            'kind' => 'country', 'country_code' => 'GB', 'display_label' => $staleCountry->name,
        ]);
        $campaign->unsetRelation('targetingSet');
        $state = $campaign->published_state;
        $state['locations'] = ['countries' => ['US']];
        $campaign->update(['published_state' => $state]);
        $campaign = $campaign->fresh();
        $plan = $this->plan($campaign, $mapping, 'add', [
            'countries' => ['US'], 'cities' => [], 'regions' => [],
        ]);

        $saved = app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);

        $this->assertSame('override', $saved->targetingSet->mode);
        $this->assertSame(['US'], app(TargetingSelections::class)->countries($saved));
        $this->assertSame(['US'], $saved->targetingSet->locations()->where('kind', 'country')->pluck('country_code')->all());
    }

    public function test_stale_baseline_rolls_back_without_changing_selections(): void
    {
        [$campaign, $mapping] = $this->campaign('meta');
        $plan = $this->plan($campaign, $mapping, 'add', [
            'countries' => ['GB', 'US'], 'cities' => [], 'regions' => [],
        ]);
        $campaign->update(['published_state' => array_replace($campaign->published_state, ['budget' => '12'])]);

        try {
            app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);
            $this->fail('Changed published state must stop a local commit.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Reconcile', $exception->getMessage());
        }

        $this->assertFalse($campaign->fresh()->targetingSet()->exists());
        $this->assertSame('12', $campaign->fresh()->published_state['budget']);
    }

    public function test_google_complete_selection_and_whole_country_restore_preserve_other_country_and_budget(): void
    {
        [$campaign, $city] = $this->campaign('google');
        $location = Location::factory()->create(['type' => 'region', 'name' => 'Texas', 'country_code' => 'US']);
        $region = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'google',
            'external_id' => 'geoTargetConstants/21176', 'provider_name' => 'Texas, United States',
        ]);
        $before = ['geo_targets' => ['geoTargetConstants/2826', 'geoTargetConstants/2840']];
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->once()->andReturn(['status' => 'matches', 'actual' => $before]);
        $this->app->instance(PublishedLocationReadback::class, $readback);
        $plan = app(PublishedLocationChangePlanner::class)->previewGoogleSelection($campaign, 'US', [$city->id, $region->id], 0);
        $this->assertSame(['geo_targets' => ['geoTargetConstants/1016864', 'geoTargetConstants/21176', 'geoTargetConstants/2826']], $plan['after']);
        $saved = app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);
        $this->assertSame(1, $saved->targetingSet->revision);
        $this->assertEqualsCanonicalizing([$city->id, $region->id], $saved->targetingSet->locations()->whereIn('kind', ['city', 'region'])->pluck('platform_location_id')->all());
        $this->assertSame('10', $saved->published_state['budget']);
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->once()->andReturn(['status' => 'matches', 'actual' => $plan['after']]);
        $this->app->instance(PublishedLocationReadback::class, $readback);
        $restore = app(PublishedLocationChangePlanner::class)->previewGoogleSelection($saved, 'US', [], 1);
        $this->assertSame($before, $restore['after']);
        $saved = app(PublishedLocationLocalCommitter::class)->commit($saved, $restore);
        $this->assertSame([], $saved->published_state['targeting_locations']);
        $this->assertSame(2, $saved->targetingSet->revision);
        $this->assertSame('10', $saved->published_state['budget']);
    }

    public function test_google_selection_refuses_commit_after_campaign_identity_changes(): void
    {
        [$campaign, $city] = $this->campaign('google');
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->once()->andReturn(['status' => 'matches', 'actual' => [
            'geo_targets' => ['geoTargetConstants/2826', 'geoTargetConstants/2840'],
        ]]);
        $this->app->instance(PublishedLocationReadback::class, $readback);
        $plan = app(PublishedLocationChangePlanner::class)->previewGoogleSelection($campaign, 'US', [$city->id], 0);
        $campaign->update(['external_campaign_id' => '67890']);
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Reconcile');
        app(PublishedLocationLocalCommitter::class)->commit($campaign, $plan);
    }

    public function test_approved_google_selection_changes_and_restores_provider_and_saved_locations(): void
    {
        config([
            'platforms.guardrails.google_published_location_edits_enabled' => true,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 100,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);
        [$campaign, $city] = $this->campaign('google');
        $regionLocation = Location::factory()->create(['type' => 'region', 'name' => 'Texas', 'country_code' => 'US']);
        $region = PlatformLocation::factory()->create([
            'location_id' => $regionLocation->id, 'platform' => 'google',
            'external_id' => 'geoTargetConstants/21176', 'provider_name' => 'Texas, United States',
        ]);
        $this->actingAs($campaign->user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-location-selection');
        $workspace->ownedBy($campaign->user);
        $workspace->focusOn($campaign);
        $current = ['geoTargetConstants/2826', 'geoTargetConstants/2840'];
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->andReturnUsing(function () use (&$current): array {
            return ['status' => 'matches', 'actual' => ['geo_targets' => $current]];
        });
        $this->app->instance(PublishedLocationReadback::class, $readback);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->twice()->andReturnUsing(function () use (&$current): array {
            return array_map(fn (string $id): array => [
                'geo_target' => $id, 'criterion' => 'customers/1234567890/campaignCriteria/12345~'.substr($id, 19),
                'negative' => false, 'status' => 'ENABLED', 'target_type' => 'Country',
            ], $current);
        });
        $google->shouldReceive('replaceCampaignLocationCriteria')->twice()->andReturnUsing(
            function ($connection, string $campaignId, array $before, array $after) use (&$current): void {
                $this->assertSame('12345', $campaignId);
                $current = $after;
            },
        );
        $this->app->instance(GoogleAdsService::class, $google);
        $tool = app(ApplyPublishedLocationChange::class);
        $request = new Request([
            'operation' => 'set_places', 'country_code' => 'US',
            'mapping_ids' => [$city->id, $region->id], 'expected_revision' => 0,
        ], 'google-selection');
        $this->assertNotNull($tool->shouldRequestApproval($request));
        $result = json_decode((string) $tool->handle($request), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['geoTargetConstants/1016864', 'geoTargetConstants/21176', 'geoTargetConstants/2826'], $current);
        $this->assertCount(2, $campaign->fresh()->published_state['targeting_locations']);

        $restore = new Request([
            'operation' => 'set_places', 'country_code' => 'US', 'mapping_ids' => [], 'expected_revision' => 1,
        ], 'google-selection-restore');
        $this->assertNotNull($tool->shouldRequestApproval($restore));
        $result = json_decode((string) $tool->handle($restore), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['geoTargetConstants/2826', 'geoTargetConstants/2840'], $current);
        $this->assertSame([], $campaign->fresh()->published_state['targeting_locations']);
    }
}
