<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\LocationCatalog;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Models\Location;
use App\Models\PlatformConnection;
use App\Models\PlatformLocation;
use App\Models\TargetingSet;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class ImportLocationCatalogTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    public function test_command_imports_provider_results_as_database_candidates(): void
    {
        $this->seedVerifiedCountries();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->twice()->with('meta', 'city', 'US', 'New York', 'act_123', 1)
            ->andReturn([[
                'platform' => 'meta', 'external_id' => '2490299', 'kind' => 'city',
                'name' => 'New York', 'label' => 'New York, New York, US',
                'country_code' => 'US', 'parent_external_id' => '3847',
            ]]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--account' => 'act_123', '--query' => ['New York'],
        ])->assertExitCode(0);

        $mapping = PlatformLocation::query()->where('platform', 'meta')->where('external_id', '2490299')->firstOrFail();
        $this->assertSame('unverified', $mapping->status);
        $this->assertNull($mapping->verified_at);
        $this->assertSame(1, $mapping->catalog_priority);
        $this->assertSame('city', $mapping->location->type);
        $this->assertSame('US', $mapping->location->country_code);
        $this->assertSame([['id' => (string) $mapping->id, 'label' => 'New York, New York, US']],
            app(LocationCatalog::class)->choices('meta', 'city', 'US'));

        $mapping->update(['status' => 'verified', 'verified_at' => now()]);
        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--account' => 'act_123', '--query' => ['New York'],
        ])->assertExitCode(0);
        $this->assertSame('verified', $mapping->fresh()->status);
        $this->assertSame(1, $mapping->fresh()->catalog_priority);
    }

    public function test_explicit_city_query_prioritizes_its_exact_match_over_partial_matches(): void
    {
        $this->seedVerifiedCountries();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'city', 'US', 'Phoenix', 'act_123', 1)
            ->andReturn([
                ['platform' => 'meta', 'external_id' => '1', 'kind' => 'city', 'name' => 'Phoenix',
                    'label' => 'Phoenix, Arizona, US', 'country_code' => 'US', 'parent_external_id' => null],
                ['platform' => 'meta', 'external_id' => '2', 'kind' => 'city', 'name' => 'Phoenixville',
                    'label' => 'Phoenixville, Pennsylvania, US', 'country_code' => 'US', 'parent_external_id' => null],
            ]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--account' => 'act_123', '--query' => ['Phoenix'],
        ])->assertExitCode(0);

        $this->assertSame(['Phoenix, Arizona, US', 'Phoenixville, Pennsylvania, US'],
            array_column(app(LocationCatalog::class)->choices('meta', 'city', 'US'), 'label'));
        $this->assertSame(1, PlatformLocation::query()->where('external_id', '1')->firstOrFail()->catalog_priority);
        $this->assertSame(0, PlatformLocation::query()->where('external_id', '2')->firstOrFail()->catalog_priority);
    }

    public function test_command_can_resolve_names_already_imported_on_another_platform(): void
    {
        $this->seedVerifiedCountries();
        config(['services.meta.ad_account_id' => 'act_configured']);
        PlatformConnection::factory()->meta()->create(['account_id' => 'act_123']);
        Location::factory()->create([
            'type' => 'region', 'name' => 'Illinois', 'country_code' => 'US',
            'iso_code' => null, 'source' => 'google', 'source_key' => 'geoTargetConstants/21116',
        ]);
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'region', 'US', 'Illinois', 'act_123', 1)
            ->andReturn([[
                'platform' => 'meta', 'external_id' => '3847', 'kind' => 'region',
                'name' => 'Illinois', 'label' => 'Illinois, US',
                'country_code' => 'US', 'parent_external_id' => null,
            ]]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'region', 'country' => 'US',
            '--from-database' => true,
        ])->assertExitCode(0);

        $this->assertCount(1, app(LocationCatalog::class)->choices('meta', 'region', 'US'));
    }

    public function test_database_name_batches_exclude_new_names_from_the_imported_platform(): void
    {
        $this->seedVerifiedCountries();
        foreach ([['Atlanta', 'google'], ['Boston', 'google'], ['Albany', 'meta']] as [$name, $source]) {
            Location::factory()->create([
                'type' => 'city', 'name' => $name, 'country_code' => 'US',
                'iso_code' => null, 'source' => $source, 'source_key' => $source.'-'.$name,
            ]);
        }
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'city', 'US', 'Boston', 'act_123', 1)
            ->andReturn([]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--account' => 'act_123', '--from-database' => true, '--offset' => 1, '--limit' => 1,
        ])->expectsOutput('Next batch: --offset=2 --limit=1.')
            ->assertExitCode(0);
    }

    public function test_database_batch_reports_the_failed_name_offset_for_resuming(): void
    {
        $this->seedVerifiedCountries();
        foreach (['Atlanta', 'Boston'] as $name) {
            Location::factory()->create([
                'type' => 'city', 'name' => $name, 'country_code' => 'US',
                'iso_code' => null, 'source' => 'google', 'source_key' => 'google-'.$name,
            ]);
        }
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'city', 'US', 'Atlanta', 'act_123', 1)
            ->andReturn([]);
        $discovery->shouldReceive('search')->once()->with('meta', 'city', 'US', 'Boston', 'act_123', 1)
            ->andThrow(new \RuntimeException('Provider is busy.'));
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--account' => 'act_123', '--from-database' => true, '--limit' => 2,
        ])->expectsOutput('Resume with --offset=1 --limit=2.')
            ->assertExitCode(1);
    }

    public function test_database_batch_finishes_cleanly_when_offset_exceeds_known_names(): void
    {
        $this->seedVerifiedCountries();

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--account' => 'act_123', '--from-database' => true, '--offset' => 500, '--limit' => 50,
        ])->expectsOutput('No more database names to import.')
            ->assertExitCode(0);
    }

    public function test_command_imports_an_entire_google_dma_catalog_without_search_terms(): void
    {
        $this->seedVerifiedCountries();
        config([
            'services.google_ads.refresh_token' => 'test-refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);
        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('geoTargetCatalog')->once()->withArgs(fn ($connection, $kind, $country, $account): bool => $kind === 'dma' && $country === 'US' && $account === '1234567890' && $connection->customer_id === $account)
            ->andReturn([[
                'platform' => 'google', 'external_id' => 'geoTargetConstants/200501', 'kind' => 'dma',
                'name' => 'New York', 'label' => 'New York DMA, United States',
                'country_code' => 'US', 'parent_external_id' => 'geoTargetConstants/2840',
            ]]);
        $this->app->instance(GoogleAdsService::class, $google);

        $this->artisan('locations:import', [
            'platform' => 'google', 'kind' => 'dma', 'country' => 'US',
            '--all' => true,
        ])->assertExitCode(0);

        $this->assertSame('New York DMA, United States', app(LocationCatalog::class)->choices('google', 'dma', 'US')[0]['label']);
    }

    public function test_command_imports_meta_dma_from_provider_search(): void
    {
        $this->seedVerifiedCountries();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'dma', 'US', 'New York', 'act_123', 1)
            ->andReturn([[
                'platform' => 'meta', 'external_id' => 'COMSCORE_MARKET:501', 'kind' => 'dma',
                'name' => 'New York', 'label' => 'New York, US',
                'country_code' => 'US', 'parent_external_id' => null,
            ]]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'dma', 'country' => 'US',
            '--account' => 'act_123', '--query' => ['New York'],
        ])->assertExitCode(0);

        $this->assertSame('New York, US', app(LocationCatalog::class)->choices('meta', 'dma', 'US')[0]['label']);
    }

    public function test_command_uses_configured_linkedin_account_when_no_override_is_given(): void
    {
        $this->seedVerifiedCountries();
        config(['platforms.linkedin.ad_account_id' => '123456']);
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('linkedin', 'dma', 'US', 'New York', '123456', 1)
            ->andReturn([]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->artisan('locations:import', [
            'platform' => 'linkedin', 'kind' => 'dma', 'country' => 'US',
            '--query' => ['New York'],
        ])->assertExitCode(0);
    }

    public function test_command_reports_when_no_account_can_be_resolved(): void
    {
        $this->seedVerifiedCountries();
        config(['services.meta.ad_account_id' => null]);

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'city', 'country' => 'US',
            '--query' => ['New York'],
        ])->expectsOutput('No connected meta ad account is configured. Connect an account or pass --account.')
            ->assertExitCode(1);
    }

    public function test_command_rejects_google_account_that_differs_from_connected_customer(): void
    {
        $this->seedVerifiedCountries();
        config([
            'services.google_ads.refresh_token' => 'test-refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);

        $this->artisan('locations:import', [
            'platform' => 'google', 'kind' => 'city', 'country' => 'US',
            '--account' => '9999999999', '--all' => true,
        ])->expectsOutput('The Google account must match the connected Google Ads customer.')
            ->assertExitCode(1);
    }

    public function test_catalog_puts_previously_targeted_database_cities_first(): void
    {
        $this->seedVerifiedCountries();
        $atlanta = Location::factory()->create(['type' => 'city', 'name' => 'Atlanta', 'country_code' => 'US', 'iso_code' => null]);
        $newYork = Location::factory()->create(['type' => 'city', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        PlatformLocation::factory()->create(['location_id' => $atlanta->id, 'platform' => 'meta', 'provider_name' => 'Atlanta, Georgia, US']);
        $mapping = PlatformLocation::factory()->create(['location_id' => $newYork->id, 'platform' => 'meta', 'provider_name' => 'New York, New York, US']);
        $set = TargetingSet::factory()->create();
        $set->locations()->create([
            'location_id' => $newYork->id, 'platform_location_id' => $mapping->id,
            'operation' => 'include', 'kind' => 'city', 'country_code' => 'US',
            'display_label' => $mapping->provider_name,
        ]);

        $this->assertSame(['New York, New York, US', 'Atlanta, Georgia, US'],
            array_column(app(LocationCatalog::class)->choices('meta', 'city', 'US'), 'label'));
    }

    public function test_command_rejects_an_unsupported_market_scope_without_importing(): void
    {
        $this->seedVerifiedCountries();

        $this->artisan('locations:import', [
            'platform' => 'meta', 'kind' => 'dma', 'country' => 'CA',
            '--account' => 'act_123', '--query' => ['Toronto'],
        ])->assertExitCode(1);

        $this->assertSame([], app(LocationCatalog::class)->choices('meta', 'dma', 'CA'));
    }
}
