<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\CountryCatalog;
use App\Campaigns\Targeting\CountryLookup;
use App\Models\AllowedAdAccount;
use App\Models\ApiCall;
use App\Services\Meta\GraphApi;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\CallLogger;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class CountryProviderRequestsTest extends TestCase
{
    use RefreshDatabase;

    public function test_meta_resolves_a_country_from_the_geolocation_search_response(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['key' => 'CA', 'type' => 'country', 'name' => 'Canada'],
            ]]),
        ]);

        $result = app(CountryLookup::class)->find('meta', 'CA', 'Canada', 'act_123');

        $this->assertSame(['id' => 'CA', 'name' => 'Canada'], $result);
        Http::assertSent(function (Request $request): bool {
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            return $request->method() === 'GET'
                && ($query['type'] ?? null) === 'adgeolocation'
                && ($query['q'] ?? null) === 'Canada'
                && json_decode((string) ($query['location_types'] ?? ''), true) === ['country'];
        });
        Http::assertSentCount(1);
    }

    public function test_linkedin_resolves_only_the_exact_country_geo_urn(): void
    {
        AllowedAdAccount::factory()->linkedin('123')->create();
        config(['platforms.linkedin.token' => 'test-token', 'platforms.linkedin.version' => '202609']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
                ['urn' => 'urn:li:geo:102095887', 'name' => 'California, United States'],
                ['urn' => 'urn:li:geo:999', 'name' => 'Canada'],
            ]]),
        ]);

        $result = app(CountryLookup::class)->find('linkedin', 'CA', 'Canada', '123');

        $this->assertSame(['id' => 'urn:li:geo:999', 'name' => 'Canada'], $result);
        Http::assertSent(function (Request $request): bool {
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            return $request->method() === 'GET'
                && ($query['q'] ?? null) === 'typeahead'
                && ($query['facet'] ?? null) === 'urn:li:adTargetingFacet:locations'
                && ($query['queryVersion'] ?? null) === 'QUERY_USES_URNS'
                && ($query['query'] ?? null) === 'Canada'
                && ! array_key_exists('locale.language', $query)
                && ! array_key_exists('locale.country', $query);
        });
        Http::assertSentCount(1);
    }

    public function test_meta_refuses_ambiguous_exact_country_results(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['key' => 'CA', 'type' => 'country', 'name' => 'Canada'],
                ['key' => 'CA', 'type' => 'country', 'name' => 'Canada duplicate'],
            ]]),
        ]);

        $this->assertNull(app(CountryLookup::class)->find('meta', 'CA', 'Canada', 'act_123'));
        Http::assertSentCount(1);
    }

    public function test_meta_searches_and_validates_interest_ids_on_the_selected_ad_account(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/act_123/targetingsearch*' => Http::response(['data' => [
                ['id' => '6001', 'name' => 'Medical students', 'audience_size_lower_bound' => 50000],
            ]]),
            'https://graph.facebook.com/v25.0/act_123/targetingvalidation*' => Http::response(['data' => [
                ['id' => '6001', 'name' => 'Medical students', 'valid' => true],
            ]]),
        ]);

        $meta = app(Meta::class);
        $matches = $meta->targetingInterests('act_123', 'medical students');
        $validated = $meta->validateTargetingInterests('act_123', ['6001']);

        $this->assertSame('6001', $matches[0]['id']);
        $this->assertTrue($validated[0]['valid']);
        Http::assertSentCount(2);

        $meta->targetingInterests('act_123', 'medical students');
        Http::assertSentCount(2);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/act_123/targetingsearch')
            && $request['q'] === 'medical students'
            && $request['limit_type'] === 'interests');
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/act_123/targetingvalidation')
            && json_decode((string) $request['targeting_list'], true) === [[
                'type' => 'interests', 'id' => '6001',
            ]]);
    }

    public function test_meta_loads_demographics_from_the_category_search(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['id' => '6002714398172', 'name' => 'Newlywed (1 year)', 'type' => 'life_events', 'path' => ['Demographics', 'Life events', 'Newlywed (1 year)']],
            ]]),
        ]);

        $meta = app(Meta::class);
        $rows = $meta->targetingBrowse('act_123', 'demographics');

        $this->assertSame('Newlywed (1 year)', $rows[0]['name']);
        $this->assertSame('life_events', $rows[0]['type']);
        Http::assertSentCount(1);
        Http::assertSent(function (Request $request): bool {
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            return $request->method() === 'GET'
                && str_contains($request->url(), '/search')
                && ! str_contains($request->url(), 'targetingbrowse')
                && ($query['type'] ?? null) === 'adTargetingCategory'
                && ($query['class'] ?? null) === 'demographics';
        });

        $meta->targetingBrowse('act_123', 'demographics');
        Http::assertSentCount(1);
    }

    public function test_meta_targeting_catalog_cache_is_cross_instance_and_still_checks_current_permissions(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.version' => 'v25.0',
            'platforms.meta.discovery_cache.targeting_catalog' => 3600,
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['id' => '6002714398172', 'name' => 'Newlywed (1 year)', 'type' => 'life_events', 'path' => ['Demographics', 'Life events', 'Newlywed (1 year)']],
            ]]),
        ]);

        $rows = app(Meta::class)->targetingBrowse('act_123', 'demographics');
        $this->app->forgetInstance(Meta::class);
        $this->app->forgetInstance(GraphApi::class);
        $this->app->forgetInstance(CallLogger::class);

        $this->assertSame($rows, app(Meta::class)->targetingBrowse('act_123', 'demographics'));
        Http::assertSentCount(1);
        $this->assertSame(1, ApiCall::count());

        AllowedAdAccount::query()->forPlatform('meta')->where('account_id', 'act_123')->update(['is_active' => false]);

        try {
            app(Meta::class)->targetingBrowse('act_123', 'demographics');
            $this->fail('Cached targeting data must still respect current account authorization.');
        } catch (MetaException) {
            $this->assertSame(1, ApiCall::count());
        }
        Http::assertSentCount(1);
    }

    public function test_empty_meta_targeting_catalog_results_are_not_persistently_cached(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.version' => 'v25.0',
            'platforms.meta.discovery_cache.targeting_catalog' => 3600,
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::sequence()
                ->push(['data' => []])
                ->push(['data' => [['id' => '6001', 'name' => 'Recovered result', 'type' => 'life_events']]]),
        ]);

        $this->assertSame([], app(Meta::class)->targetingBrowse('act_123', 'demographics'));
        $this->app->forgetInstance(Meta::class);
        $this->app->forgetInstance(GraphApi::class);
        $this->app->forgetInstance(CallLogger::class);

        $this->assertSame('Recovered result', app(Meta::class)->targetingBrowse('act_123', 'demographics')[0]['name']);
        Http::assertSentCount(2);
    }

    public function test_related_targeting_suggestions_use_the_account_scoped_discovery_cache(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.version' => 'v25.0',
            'platforms.meta.discovery_cache.targeting_catalog' => 3600,
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/act_123/targetingsuggestions*' => Http::response(['data' => [
                ['id' => '6001', 'name' => 'Related interest', 'type' => 'interests'],
            ]]),
        ]);
        $targeting = [['type' => 'interests', 'id' => '6000']];

        $result = app(Meta::class)->targetingSuggestions('act_123', $targeting);
        $this->app->forgetInstance(Meta::class);
        $this->app->forgetInstance(GraphApi::class);
        $this->app->forgetInstance(CallLogger::class);

        $this->assertSame($result, app(Meta::class)->targetingSuggestions('act_123', $targeting));
        Http::assertSentCount(1);
        $this->assertSame(1, ApiCall::count());
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/act_123/targetingsuggestions')
            && json_decode((string) $request['targeting_list'], true) === $targeting);
    }

    public function test_meta_creates_a_website_audience_from_an_event_and_retention_window(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/act_123/customaudiences' => Http::response(['id' => '7001']),
        ]);

        $created = app(Meta::class)->createWebsiteAudience('act_123', 'Winter Sale - Purchase', '456', 'Purchase', 30);

        $this->assertSame('7001', $created['id']);
        Http::assertSent(fn (Request $request): bool => $request->method() === 'POST'
            && str_contains($request->url(), '/act_123/customaudiences'));
        $sent = Http::recorded()->last()[0];
        $rule = json_decode((string) $sent['rule'], true);

        $this->assertSame('30', (string) $sent['retention_days']);
        $this->assertTrue(in_array((string) $sent['prefill'], ['1', 'true'], true));
        $this->assertSame(['id' => '456', 'type' => 'pixel'], data_get($rule, 'inclusions.rules.0.event_sources.0'));
        $this->assertSame(2592000, data_get($rule, 'inclusions.rules.0.retention_seconds'));
        $this->assertSame([
            'field' => 'event', 'operator' => '=', 'value' => 'Purchase',
        ], data_get($rule, 'inclusions.rules.0.filter.filters.0'));
    }

    public function test_google_resolves_an_enabled_country_by_iso_code(): void
    {
        AllowedAdAccount::factory()->google('1234567890')->create();
        config([
            'services.google_ads.refresh_token' => 'test-refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
            'services.google_ads.oauth_client_id' => 'test-client',
            'services.google_ads.oauth_client_secret' => 'test-secret',
            'services.google_ads.developer_token' => 'test-developer-token',
            'services.google_ads.api_version' => 'v25',
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/v25/customers/1234567890/googleAds:searchStream' => Http::response([['results' => [
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/2124', 'name' => 'Canada', 'countryCode' => 'CA', 'targetType' => 'Country', 'status' => 'ENABLED']],
            ]]]),
        ]);

        $result = app(CountryLookup::class)->find('google', 'CA', 'Canada', '1234567890');

        $this->assertSame(['id' => 'geoTargetConstants/2124', 'name' => 'Canada'], $result);
        Http::assertSent(fn (Request $request): bool => $request->method() === 'POST'
            && str_contains($request->url(), '/googleAds:searchStream')
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.country_code = 'CA'")
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.target_type = 'Country'"));
        Http::assertSentCount(2);
    }

    public function test_google_refuses_two_distinct_enabled_country_targets_for_one_code(): void
    {
        AllowedAdAccount::factory()->google('1234567890')->create();
        config([
            'services.google_ads.refresh_token' => 'test-refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
            'services.google_ads.oauth_client_id' => 'test-client',
            'services.google_ads.oauth_client_secret' => 'test-secret',
            'services.google_ads.developer_token' => 'test-developer-token',
            'services.google_ads.api_version' => 'v25',
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/v25/customers/1234567890/googleAds:searchStream' => Http::response([['results' => [
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/2124', 'name' => 'Canada', 'countryCode' => 'CA', 'targetType' => 'Country', 'status' => 'ENABLED']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/9999', 'name' => 'Canada', 'countryCode' => 'CA', 'targetType' => 'Country', 'status' => 'ENABLED']],
            ]]]),
        ]);

        $this->assertNull(app(CountryLookup::class)->find('google', 'CA', 'Canada', '1234567890'));
        Http::assertSentCount(2);
    }

    public function test_provider_authentication_failure_does_not_save_a_mapping(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'expired-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response([
                'error' => ['message' => 'Invalid OAuth access token', 'type' => 'OAuthException', 'code' => 190],
            ], 401),
        ]);

        try {
            app(CountryCatalog::class)->resolve('meta', ['CA'], 'act_123');
            $this->fail('An authentication failure must stop country resolution.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('Invalid OAuth access token', $exception->getMessage());
        }

        $this->assertDatabaseCount('platform_locations', 0);
        Http::assertSentCount(1);
    }
}
