<?php

namespace Tests\Feature;

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 Illuminate\Foundation\Testing\RefreshDatabase;
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']);
    }
}
