<?php

namespace Tests\Feature;

use App\Campaigns\Publisher;
use App\Campaigns\PublishGate;
use App\Campaigns\Targeting\CountryLookup;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\PlatformLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Mockery;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class CountryApprovalSnapshotTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    protected function setUp(): void
    {
        parent::setUp();

        $this->seedVerifiedCountries();
        Http::preventStrayRequests();
    }

    private function publisher(): Publisher
    {
        $gate = Mockery::mock(PublishGate::class);
        $gate->shouldReceive('check')->andReturn([]);
        $this->app->instance(PublishGate::class, $gate);

        return app(Publisher::class);
    }

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

    private function mapping(string $platform): PlatformLocation
    {
        return PlatformLocation::query()
            ->where('platform', $platform)
            ->whereHas('location', fn ($query) => $query->where('iso_code', 'US'))
            ->sole();
    }

    public function test_changed_provider_country_ids_block_approval_on_every_platform(): void
    {
        $publisher = $this->publisher();

        foreach (['meta' => 'CA', 'google' => 'geoTargetConstants/9999', 'linkedin' => 'urn:li:geo:9999'] as $platform => $newId) {
            $campaign = $this->campaign($platform);
            $proposal = $publisher->propose($campaign, 'test');
            $this->assertSame('proposed', $proposal->state);
            $this->assertSame($this->mapping($platform)->external_id, $proposal->params['country_targeting']['mappings']['US']['external_id']);

            $this->mapping($platform)->update(['external_id' => $newId]);

            $decision = $publisher->approve($proposal, 'test');
            $this->assertSame('blocked', $decision->state, $platform);
            $this->assertStringContainsString('changed since review', $decision->reason);
            $this->assertSame('draft', $campaign->fresh()->status);
        }

        Http::assertNothingSent();
    }

    public function test_unresolved_country_blocks_the_publish_proposal(): void
    {
        $lookup = Mockery::mock(CountryLookup::class);
        $lookup->shouldReceive('find')->once()->andReturn(null);
        $this->app->instance(CountryLookup::class, $lookup);

        $campaign = $this->campaign('linkedin');
        $campaign->update(['locations' => ['countries' => ['ZA']]]);
        $proposal = $this->publisher()->propose($campaign, 'test');

        $this->assertSame('blocked', $proposal->state);
        $this->assertStringContainsString('country targeting could not be verified', $proposal->reason);
        Http::assertNothingSent();
    }

    public function test_recreated_mapping_cannot_reuse_an_old_approval_even_with_the_same_provider_id(): void
    {
        $publisher = $this->publisher();
        $campaign = $this->campaign('meta');
        $proposal = $publisher->propose($campaign, 'test');
        $mapping = $this->mapping('meta');

        $mapping->delete();
        PlatformLocation::query()->create([
            'location_id' => $mapping->location_id,
            'platform' => 'meta',
            'external_id' => $mapping->external_id,
            'provider_name' => $mapping->provider_name,
            'status' => 'verified',
            'verified_at' => now(),
        ]);

        $decision = $publisher->approve($proposal, 'test');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('changed since review', $decision->reason);
        Http::assertNothingSent();
    }

    public function test_failed_country_reverification_blocks_approval_before_any_provider_call(): void
    {
        $lookup = Mockery::mock(CountryLookup::class);
        $lookup->shouldReceive('find')->once()->andReturn(null);
        $this->app->instance(CountryLookup::class, $lookup);

        $publisher = $this->publisher();
        $campaign = $this->campaign('linkedin');
        $proposal = $publisher->propose($campaign, 'test');
        $this->mapping('linkedin')->delete();

        $decision = $publisher->approve($proposal, 'test');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('country targeting could not be verified', $decision->reason);
        Http::assertNothingSent();
    }

    public function test_account_or_targeting_revision_change_blocks_an_old_approval(): void
    {
        $publisher = $this->publisher();
        $campaign = $this->campaign('linkedin');
        $proposal = $publisher->propose($campaign, 'test');
        $campaign->update(['ad_account_id' => '509999998']);

        $this->assertSame('blocked', $publisher->approve($proposal, 'test')->state);

        // A real change, not the same countries saved twice.
        //
        // This saved ['US'] both times and relied on the second save bumping the
        // revision. saveCampaignCountries() now returns early when the countries
        // are identical, which is right - re-saving what is already there is not
        // an edit, and bumping the revision for it invalidated geography options
        // the user was still looking at. But it left this asserting that an
        // unchanged campaign blocks its own approval, which is not the rule and
        // not what the test is named after.
        //
        // Without a real change the approval proceeded, so a LinkedIn publish was
        // attempted and the run failed on the call guard rather than here, which
        // is how a no-op in targeting surfaced as "No ad accounts are allowed".
        $campaign = $this->campaign('linkedin');
        $selections = app(TargetingSelections::class);
        $selections->saveCampaignCountries($campaign, ['US']);
        $proposal = $publisher->propose($campaign, 'test');
        $selections->saveCampaignCountries($campaign, ['US', 'GB']);

        $this->assertSame('blocked', $publisher->approve($proposal, 'test')->state);
        Http::assertNothingSent();
    }

    /**
     * And re-saving the same countries is deliberately not a change.
     *
     * The other half of the behaviour above, pinned so nobody restores the
     * revision bump to make the old assertion pass again.
     */
    public function test_saving_the_same_countries_twice_does_not_invalidate_an_approval(): void
    {
        $selections = app(TargetingSelections::class);
        $campaign = $this->campaign('linkedin');
        $selections->saveCampaignCountries($campaign, ['US']);

        $before = (int) $campaign->targetingSet()->value('revision');
        $selections->saveCampaignCountries($campaign, ['US']);

        $this->assertSame($before, (int) $campaign->fresh()->targetingSet()->value('revision'));
    }
}
