<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\PublishedLocationChangePlanner;
use App\Campaigns\Targeting\PublishedLocationReadback;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Mockery;
use RuntimeException;
use Tests\TestCase;

class PublishedLocationChangePlannerTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $platform, ?PlatformLocation $selected = null): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(),
            'name' => 'Published location plan',
            'platform' => $platform,
            'status' => 'draft',
            'ad_account_id' => $platform === 'meta' ? 'act_111' : '1234567890',
            'locations' => ['countries' => ['US', 'GB']],
        ]);

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

        $campaign->update([
            'status' => 'published',
            'external_campaign_id' => '12345',
            'published_state' => ['locations' => ['countries' => ['US', 'GB']], 'targeting_locations' => []],
        ]);

        return $campaign->fresh();
    }

    private function mapping(string $platform, string $kind, string $externalId): PlatformLocation
    {
        $location = Location::factory()->create([
            'type' => $kind,
            'name' => $kind === 'city' ? 'Springfield' : 'United States',
            'country_code' => 'US',
            'iso_code' => $kind === 'country' ? 'US' : null,
            'source' => $platform,
            'source_key' => $externalId,
        ]);

        return PlatformLocation::factory()->create([
            'location_id' => $location->getKey(),
            'platform' => $platform,
            'external_id' => $externalId,
            'provider_name' => $kind === 'city' ? 'Springfield, Illinois, US' : 'United States',
        ]);
    }

    /** @param array<string, mixed> $actual */
    private function readback(string $platform, array $actual, string $status = 'matches'): void
    {
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->once()->andReturn([
            'status' => $status,
            'platform' => $platform,
            'expected' => $actual,
            'actual' => $actual,
        ]);
        $this->app->instance(PublishedLocationReadback::class, $readback);
    }

    public function test_meta_preview_narrows_only_the_first_city_country_without_writing(): void
    {
        Http::fake();
        $city = $this->mapping('meta', 'city', '2440704');
        $campaign = $this->campaign('meta');
        $this->readback('meta', ['countries' => ['GB', 'US'], 'cities' => [], 'regions' => []]);

        $plan = app(PublishedLocationChangePlanner::class)->preview($campaign, 'add', $city->getKey(), 0);

        $this->assertSame(['countries' => ['GB'], 'cities' => ['2440704'], 'regions' => []], $plan['after']);
        $this->assertSame('Springfield, Illinois, US', $plan['place']['label']);
        $this->assertSame(0, $campaign->fresh()->targetingSet()->value('revision') ?? 0);
        $this->assertFalse($campaign->targetingSet()->exists());
        Http::assertNothingSent();
    }

    public function test_meta_preview_restores_whole_country_after_removing_its_last_city(): void
    {
        $city = $this->mapping('meta', 'city', '2440704');
        $campaign = $this->campaign('meta', $city);
        $this->readback('meta', ['countries' => ['GB'], 'cities' => ['2440704'], 'regions' => []]);

        $plan = app(PublishedLocationChangePlanner::class)->preview($campaign, 'remove', $city->getKey(), 1);

        $this->assertSame(['countries' => ['GB', 'US'], 'cities' => [], 'regions' => []], $plan['after']);
        $this->assertSame(1, $campaign->fresh()->targetingSet()->value('revision'));
        $this->assertSame(1, $campaign->targetingSet->locations()->where('kind', 'city')->count());
    }

    public function test_google_preview_replaces_country_criterion_with_exact_city_and_can_reverse_it(): void
    {
        $this->mapping('google', 'country', 'geoTargetConstants/2840');
        $city = $this->mapping('google', 'city', 'geoTargetConstants/1016864');
        $campaign = $this->campaign('google');
        $this->readback('google', ['geo_targets' => ['geoTargetConstants/2826', 'geoTargetConstants/2840']]);

        $plan = app(PublishedLocationChangePlanner::class)->preview($campaign, 'add', $city->getKey(), 0);

        $this->assertSame(['geo_targets' => ['geoTargetConstants/1016864', 'geoTargetConstants/2826']], $plan['after']);
        $this->assertSame('1234567890', $plan['account_id']);

        $selected = $this->campaign('google', $city);
        $this->readback('google', ['geo_targets' => ['geoTargetConstants/1016864', 'geoTargetConstants/2826']]);
        $reverse = app(PublishedLocationChangePlanner::class)->preview($selected, 'remove', $city->getKey(), 1);

        $this->assertSame(['geo_targets' => ['geoTargetConstants/2826', 'geoTargetConstants/2840']], $reverse['after']);
        $this->assertSame(1, $selected->fresh()->targetingSet()->value('revision'));
    }

    public function test_meta_replacement_keeps_country_narrowed_in_one_plan(): void
    {
        $old = $this->mapping('meta', 'city', '2440704');
        $new = $this->mapping('meta', 'city', '2440705');
        $campaign = $this->campaign('meta', $old);
        $this->readback('meta', ['countries' => ['GB'], 'cities' => ['2440704'], 'regions' => []]);

        $plan = app(PublishedLocationChangePlanner::class)->preview($campaign, 'replace', $new->getKey(), 1, $old->getKey());

        $this->assertSame(['countries' => ['GB'], 'cities' => ['2440705'], 'regions' => []], $plan['after']);
        $this->assertSame($old->getKey(), $plan['replaced_place']['mapping_id']);
        $this->assertSame(1, $campaign->fresh()->targetingSet->revision);
    }

    public function test_google_replacement_swaps_one_criterion_without_restoring_country(): void
    {
        $old = $this->mapping('google', 'city', 'geoTargetConstants/1016864');
        $new = $this->mapping('google', 'city', 'geoTargetConstants/1016865');
        $campaign = $this->campaign('google', $old);
        $this->readback('google', ['geo_targets' => ['geoTargetConstants/1016864', 'geoTargetConstants/2826']]);

        $plan = app(PublishedLocationChangePlanner::class)->preview($campaign, 'replace', $new->getKey(), 1, $old->getKey());

        $this->assertSame(['geo_targets' => ['geoTargetConstants/1016865', 'geoTargetConstants/2826']], $plan['after']);
        $this->assertSame($old->getKey(), $plan['replaced_place']['mapping_id']);
    }

    public function test_google_included_place_edit_refuses_a_campaign_with_exclusions(): void
    {
        $city = $this->mapping('google', 'city', 'geoTargetConstants/1016864');
        $campaign = $this->campaign('google');
        $this->readback('google', [
            'geo_targets' => ['geoTargetConstants/2840'],
            'excluded_geo_targets' => ['geoTargetConstants/1023191'],
        ]);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('has location exclusions');
        app(PublishedLocationChangePlanner::class)->preview($campaign, 'add', $city->getKey(), 0);
    }

    public function test_replacement_rejects_a_place_in_another_country(): void
    {
        $old = $this->mapping('meta', 'city', '2440704');
        $new = $this->mapping('meta', 'city', '2440705');
        $new->location->update(['country_code' => 'GB']);
        $campaign = $this->campaign('meta', $old);
        $this->readback('meta', ['countries' => ['GB'], 'cities' => ['2440704'], 'regions' => []]);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('same country');
        app(PublishedLocationChangePlanner::class)->preview($campaign, 'replace', $new->getKey(), 1, $old->getKey());
    }

    public function test_preview_refuses_provider_drift_and_stale_mappings_without_any_write(): void
    {
        Http::fake();
        $city = $this->mapping('meta', 'city', '2440704');
        $campaign = $this->campaign('meta');
        $this->readback('meta', ['countries' => ['GB', 'US'], 'cities' => [], 'regions' => []], 'drift');

        try {
            app(PublishedLocationChangePlanner::class)->preview($campaign, 'add', $city->getKey(), 0);
            $this->fail('A provider mismatch must stop the plan.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('differs from the saved baseline', $exception->getMessage());
        }

        $city->update(['verified_at' => now()->subDays(31)]);
        $this->readback('meta', ['countries' => ['GB', 'US'], 'cities' => [], 'regions' => []]);

        try {
            app(PublishedLocationChangePlanner::class)->preview($campaign, 'add', $city->getKey(), 0);
            $this->fail('A stale mapping must stop the plan.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('fresh, verified', $exception->getMessage());
        }

        $this->assertFalse($campaign->targetingSet()->exists());
        Http::assertNothingSent();
    }

    public function test_changed_targeting_revision_stops_before_provider_readback(): void
    {
        $city = $this->mapping('meta', 'city', '2440704');
        $campaign = $this->campaign('meta', $city);
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldNotReceive('inspect');
        $this->app->instance(PublishedLocationReadback::class, $readback);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Targeting changed since it was opened');
        app(PublishedLocationChangePlanner::class)->preview($campaign, 'remove', $city->getKey(), 0);
    }
}
