<?php

namespace Tests\Feature;

use App\Campaigns\PendingChanges;
use App\Campaigns\Targeting\PublishedLocationProviderMutator;
use App\Campaigns\Targeting\PublishedLocationReadback;
use App\Campaigns\Targeting\PublishedLocationReconciliationRequired;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\User;
use App\Services\GoogleAdsService;
use App\Services\Meta\GraphApi;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class PublishedLocationProviderMutatorTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    #[DataProvider('providerReadbackScenarios')]
    public function test_location_edits_verify_real_transport_responses(string $platform, string $scenario): void
    {
        $this->seedVerifiedCountries();
        config([
            'platforms.guardrails.published_location_edits_enabled' => true,
            'platforms.guardrails.allowed_ad_accounts' => ['act_111', '1234567890'],
            'platforms.guardrails.max_calls_per_hour' => 100,
            'platforms.guardrails.pause_all_writes' => false,
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'services.google_ads.customer_id' => '1234567890',
            'services.google_ads.refresh_token' => 'test-refresh-token',
            'services.google_ads.oauth_client_id' => 'test-client',
            'services.google_ads.oauth_client_secret' => 'test-secret',
            'services.google_ads.developer_token' => 'test-developer',
        ]);
        Http::preventStrayRequests();
        $campaign = $this->campaign($platform);
        $campaign->update(['locations' => ['countries' => ['US']]]);
        $campaign->update(['published_state' => app(PendingChanges::class)->snapshot($campaign)]);
        $campaign = $campaign->fresh();
        $reads = 0;
        $writes = 0;
        $changed = false;
        Http::fake(function ($request) use ($platform, $scenario, &$reads, &$writes, &$changed) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'test-token', 'expires_in' => 3600]);
            }

            if (($platform === 'meta' && $request->method() === 'POST')
                || str_contains($request->url(), 'campaignCriteria:mutate')) {
                $writes++;
                $changed = $scenario !== 'confirmation_mismatch';

                return Http::response($platform === 'meta' ? ['success' => true] : ['results' => []]);
            }

            $query = (string) ($request->data()['query'] ?? '');

            if ($platform === 'meta' && str_contains($request->url(), '/adsets')) {
                $reads++;
                $geo = $changed ? ['cities' => [['key' => '2440704']]] : ['countries' => ['US']];

                return Http::response(['data' => [['id' => '67890', 'targeting' => ['age_min' => 25, 'geo_locations' => $geo]]]]);
            }

            if ($platform === 'meta') {
                return Http::response(['account_id' => '111']);
            }

            if (str_contains($query, 'FROM geo_target_constant')) {
                return Http::response([['results' => array_map(static fn (array $place): array => ['geoTargetConstant' => [
                    'resourceName' => 'geoTargetConstants/'.$place[0], 'countryCode' => 'US',
                    'targetType' => $place[1], 'canonicalName' => $place[2],
                ]], [['2840', 'Country', 'United States'], ['1016864', 'City', 'New York']])]]);
            }

            if (str_contains($query, "campaign_criterion.type = 'LOCATION'")) {
                $reads++;

                return Http::response([['results' => [['campaignCriterion' => [
                    'resourceName' => 'customers/1234567890/campaignCriteria/12345~1',
                    'location' => ['geoTargetConstant' => 'geoTargetConstants/'.($changed ? '1016864' : '2840')],
                    'negative' => false, 'status' => 'ENABLED',
                ]]]]]);
            }

            return Http::response([['results' => []]]);
        });

        $before = $platform === 'meta'
            ? ['countries' => ['US'], 'cities' => [], 'regions' => [], 'geo_markets' => []]
            : ['geo_targets' => ['geoTargetConstants/2840']];
        $after = $platform === 'meta'
            ? ['countries' => [], 'cities' => ['2440704'], 'regions' => [], 'geo_markets' => []]
            : ['geo_targets' => ['geoTargetConstants/1016864']];

        if ($scenario === 'preexisting_drift') {
            if ($platform === 'meta') {
                app(Meta::class)->adSets('12345', 'act_111');
            } else {
                app(GoogleAdsService::class)->readCampaignLocationCriteria(GoogleAdsConnection::shared(), '12345', true);
            }
            $changed = true;
        }

        try {
            $result = app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));
            $this->assertSame('success', $scenario, 'A drifted provider response must reject the edit.');
            $this->assertSame($after, $result['actual']);
        } catch (PublishedLocationReconciliationRequired $exception) {
            $this->assertSame('confirmation_mismatch', $scenario, $exception->getMessage());
        } catch (RuntimeException $exception) {
            $this->assertSame('preexisting_drift', $scenario, $exception->getMessage());
            $this->assertStringContainsString('changed since approval', $exception->getMessage());
        }

        $this->assertSame($scenario === 'preexisting_drift' ? 0 : 1, $writes);
        $this->assertSame($scenario === 'preexisting_drift' ? 2 : 3, $reads);
    }

    public static function providerReadbackScenarios(): array
    {
        return [
            ['meta', 'success'], ['google', 'success'],
            ['meta', 'preexisting_drift'], ['google', 'preexisting_drift'],
            ['meta', 'confirmation_mismatch'], ['google', 'confirmation_mismatch'],
        ];
    }

    private function campaign(string $platform): Campaign
    {
        return Campaign::create([
            'user_id' => User::factory()->create()->getKey(),
            'name' => 'Paused location edit',
            'platform' => $platform,
            'status' => 'published',
            'external_campaign_id' => '12345',
            'external_ids' => ['campaign_id' => '12345', 'adset_id' => '67890'],
            'ad_account_id' => $platform === 'meta' ? 'act_111' : '1234567890',
            'locations' => ['countries' => ['US', 'GB']],
            'published_state' => ['locations' => ['countries' => ['US', 'GB']]],
        ]);
    }

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

    /** @return array<string, mixed> */
    private function plan(Campaign $campaign, array $before, array $after): array
    {
        return [
            'campaign_id' => $campaign->getKey(), 'platform' => $campaign->platform,
            'account_id' => $campaign->ad_account_id, 'before' => $before, 'after' => $after,
        ];
    }

    public function test_meta_update_preserves_other_ad_set_targeting_and_existing_place_metadata(): void
    {
        Http::fake();
        config(['platforms.guardrails.published_location_edits_enabled' => true]);
        $campaign = $this->campaign('meta');
        $before = ['countries' => ['GB', 'US'], 'cities' => ['111'], 'regions' => [], 'geo_markets' => []];
        $after = ['countries' => ['GB'], 'cities' => ['111', '2440704'], 'regions' => [], 'geo_markets' => []];
        $this->readback('meta', $before, $after);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->with('12345')->andReturn('111');
        $meta->shouldReceive('adSets')->once()->with('12345', 'act_111', true)->andReturn([[
            'id' => '67890',
            'targeting' => [
                'age_min' => 25,
                'custom_audiences' => [['id' => 'audience-1']],
                'geo_locations' => ['countries' => ['GB', 'US'], 'cities' => [['key' => '111', 'name' => 'Existing city']]],
            ],
        ]]);
        $this->app->instance(Meta::class, $meta);
        $graph = Mockery::mock(GraphApi::class);
        $graph->shouldReceive('updateEntity')->once()->with('67890', Mockery::on(function (array $fields): bool {
            $targeting = json_decode($fields['targeting'] ?? '', true);

            return $targeting['age_min'] === 25
                && $targeting['custom_audiences'] === [['id' => 'audience-1']]
                && $targeting['geo_locations']['countries'] === ['GB']
                && $targeting['geo_locations']['cities'] === [
                    ['key' => '111', 'name' => 'Existing city'], ['key' => '2440704'],
                ];
        }), 'act_111')->andReturn(['success' => true]);
        $this->app->instance(GraphApi::class, $graph);

        $result = app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));

        $this->assertSame($after, $result['actual']);
        $this->assertSame(['US', 'GB'], $campaign->fresh()->locations['countries']);
        Http::assertNothingSent();
    }

    public function test_google_update_uses_saved_customer_and_exact_enabled_criteria(): void
    {
        config([
            'platforms.guardrails.published_location_edits_enabled' => true,
            'services.google_ads.customer_id' => '1234567890',
            'services.google_ads.refresh_token' => 'test-refresh-token',
        ]);
        $campaign = $this->campaign('google');
        $before = ['geo_targets' => ['geoTargetConstants/2840']];
        $after = ['geo_targets' => ['geoTargetConstants/1016864']];
        $this->readback('google', $before, $after);
        $criteria = [[
            'criterion' => 'customers/1234567890/campaignCriteria/12345~1',
            'geo_target' => 'geoTargetConstants/2840', 'negative' => false,
            'status' => 'ENABLED', 'target_type' => 'Country',
        ]];
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readCampaignLocationCriteria')->once()
            ->with(Mockery::type(GoogleAdsConnection::class), '12345', true, false, true)->andReturn($criteria);
        $google->shouldReceive('replaceCampaignLocationCriteria')->once()
            ->with(Mockery::type(GoogleAdsConnection::class), '12345', $criteria, $after['geo_targets']);
        $this->app->instance(GoogleAdsService::class, $google);

        $result = app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));

        $this->assertSame($after, $result['actual']);
    }

    public function test_meta_confirmed_locations_ignore_json_object_key_order(): void
    {
        config(['platforms.guardrails.published_location_edits_enabled' => true]);
        $campaign = $this->campaign('meta');
        $before = ['cities' => ['2440704'], 'regions' => [], 'countries' => [], 'geo_markets' => []];
        $after = ['cities' => ['2438177', '2440704'], 'regions' => [], 'countries' => [], 'geo_markets' => []];
        $readback = Mockery::mock(PublishedLocationReadback::class)->makePartial();
        $readback->shouldReceive('inspect')->twice()->andReturn(
            ['status' => 'matches', 'actual' => ['countries' => [], 'cities' => ['2440704'], 'regions' => [], 'geo_markets' => []]],
            ['status' => 'drift', 'actual' => ['countries' => [], 'cities' => ['2438177', '2440704'], 'regions' => [], 'geo_markets' => []]],
        );
        $this->app->instance(PublishedLocationReadback::class, $readback);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('111');
        $meta->shouldReceive('adSets')->once()->andReturn([[
            'id' => '67890', 'targeting' => ['geo_locations' => ['cities' => [['key' => '2440704']]]],
        ]]);
        $this->app->instance(Meta::class, $meta);
        $graph = Mockery::mock(GraphApi::class);
        $graph->shouldReceive('updateEntity')->once()->andReturn(['success' => true]);
        $this->app->instance(GraphApi::class, $graph);

        $result = app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));

        $this->assertSame(['2438177', '2440704'], $result['actual']['cities']);
    }

    public function test_meta_city_replacement_sends_one_narrowed_targeting_update(): void
    {
        config(['platforms.guardrails.published_location_edits_enabled' => true]);
        $campaign = $this->campaign('meta');
        $before = ['countries' => ['GB'], 'cities' => ['2440704'], 'regions' => [], 'geo_markets' => []];
        $after = ['countries' => ['GB'], 'cities' => ['2420605'], 'regions' => [], 'geo_markets' => []];
        $this->readback('meta', $before, $after);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->with('12345')->andReturn('111');
        $meta->shouldReceive('adSets')->once()->andReturn([[
            'id' => '67890',
            'targeting' => [
                'age_min' => 25,
                'geo_locations' => ['countries' => ['GB'], 'cities' => [['key' => '2440704']]],
            ],
        ]]);
        $this->app->instance(Meta::class, $meta);
        $graph = Mockery::mock(GraphApi::class);
        $graph->shouldReceive('updateEntity')->once()->with('67890', Mockery::on(function (array $fields): bool {
            $targeting = json_decode($fields['targeting'] ?? '', true);

            return $targeting['age_min'] === 25
                && $targeting['geo_locations']['countries'] === ['GB']
                && $targeting['geo_locations']['cities'] === [['key' => '2420605']];
        }), 'act_111')->andReturn(['success' => true]);
        $this->app->instance(GraphApi::class, $graph);

        $result = app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));

        $this->assertSame($after, $result['actual']);
    }

    public function test_disabled_or_drifted_edit_never_reaches_provider_write(): void
    {
        $campaign = $this->campaign('meta');
        $before = ['countries' => ['US'], 'cities' => [], 'regions' => [], 'geo_markets' => []];
        $after = ['countries' => [], 'cities' => ['2440704'], 'regions' => [], 'geo_markets' => []];
        $meta = Mockery::mock(Meta::class);
        $meta->shouldNotReceive('adSets');
        $this->app->instance(Meta::class, $meta);
        $graph = Mockery::mock(GraphApi::class);
        $graph->shouldNotReceive('updateEntity');
        $this->app->instance(GraphApi::class, $graph);

        try {
            app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));
            $this->fail('The default-off feature gate must stop edits.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('disabled', $exception->getMessage());
        }

        config(['platforms.guardrails.published_location_edits_enabled' => true]);
        $readback = Mockery::mock(PublishedLocationReadback::class);
        $readback->shouldReceive('inspect')->once()->andReturn([
            'status' => 'drift', 'platform' => 'meta',
            'expected' => $before, 'actual' => ['countries' => ['CA'], 'cities' => [], 'regions' => [], 'geo_markets' => []],
        ]);
        $this->app->instance(PublishedLocationReadback::class, $readback);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('changed since approval');
        app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));

    }

    public function test_meta_write_with_different_readback_requires_reconciliation(): void
    {
        config(['platforms.guardrails.published_location_edits_enabled' => true]);
        $campaign = $this->campaign('meta');
        $before = ['countries' => ['US'], 'cities' => [], 'regions' => [], 'geo_markets' => []];
        $after = ['countries' => [], 'cities' => ['2440704'], 'regions' => [], 'geo_markets' => []];
        $this->readback('meta', $before, ['countries' => ['US'], 'cities' => [], 'regions' => [], 'geo_markets' => []]);
        $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);
        $graph = Mockery::mock(GraphApi::class);
        $graph->shouldReceive('updateEntity')->once()->andReturn(['success' => true]);
        $this->app->instance(GraphApi::class, $graph);

        $this->expectException(PublishedLocationReconciliationRequired::class);
        $this->expectExceptionMessage('returned different location targeting');
        app(PublishedLocationProviderMutator::class)->apply($campaign, $this->plan($campaign, $before, $after));
    }
}
