<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\LocationCatalogImporter;
use App\Models\Location;
use App\Models\PlatformLocation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class LocationCatalogSnapshotTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    public function test_snapshot_round_trip_uses_provider_keys_and_preserves_existing_verified_mapping(): void
    {
        $this->seedVerifiedCountries();
        app(LocationCatalogImporter::class)->store([[
            'platform' => 'meta', 'external_id' => '2490299', 'kind' => 'city',
            'name' => 'New York', 'label' => 'New York, New York, US',
            'country_code' => 'US', 'parent_external_id' => '3847',
        ]], 'New York');
        $path = tempnam(sys_get_temp_dir(), 'location-snapshot-test-');
        unlink($path);

        try {
            $this->artisan('locations:snapshot', ['action' => 'export', 'path' => $path])->assertExitCode(0);
            $this->assertStringNotContainsString('location_id', file_get_contents($path));
            PlatformLocation::query()->delete();
            Location::query()->where('type', 'city')->delete();

            $this->artisan('locations:snapshot', ['action' => 'import', 'path' => $path])->assertExitCode(0);
            $mapping = PlatformLocation::query()->where('platform', 'meta')->where('external_id', '2490299')->firstOrFail();
            $this->assertSame('New York', $mapping->location->name);
            $this->assertSame('unverified', $mapping->status);
            $this->assertSame(1, $mapping->catalog_priority);

            $mapping->update(['status' => 'verified', 'verified_at' => now()]);
            $this->artisan('locations:snapshot', ['action' => 'import', 'path' => $path])->assertExitCode(0);
            $this->assertSame('verified', $mapping->fresh()->status);
            $this->assertSame(1, PlatformLocation::query()->count());
        } finally {
            if (is_file($path)) {
                unlink($path);
            }
        }
    }

    public function test_invalid_snapshot_is_rejected_before_any_rows_are_imported(): void
    {
        $this->seedVerifiedCountries();
        $path = tempnam(sys_get_temp_dir(), 'location-snapshot-test-');
        file_put_contents($path, implode("\n", [
            json_encode(['format' => 'arb-location-catalog', 'version' => 1]),
            json_encode([
                'platform' => 'meta', 'external_id' => '2490299', 'kind' => 'city',
                'name' => 'New York', 'label' => 'New York, US',
                'country_code' => 'US', 'parent_external_id' => null,
            ]),
            '{bad json}',
        ]));

        try {
            $this->artisan('locations:snapshot', ['action' => 'import', 'path' => $path])->assertExitCode(1);
            $this->assertSame(0, PlatformLocation::query()->where('platform', 'meta')->where('external_id', '2490299')->count());
        } finally {
            unlink($path);
        }
    }

    public function test_version_one_snapshot_remains_importable_with_default_priority(): void
    {
        $this->seedVerifiedCountries();
        $path = tempnam(sys_get_temp_dir(), 'location-snapshot-test-');
        file_put_contents($path, implode("\n", [
            json_encode(['format' => 'arb-location-catalog', 'version' => 1]),
            json_encode([
                'platform' => 'meta', 'external_id' => '2490299', 'kind' => 'city',
                'name' => 'New York', 'label' => 'New York, US',
                'country_code' => 'US', 'parent_external_id' => null,
            ]),
        ]));

        try {
            $this->artisan('locations:snapshot', ['action' => 'import', 'path' => $path])
                ->expectsOutputToContain('Importing 1 location candidates...')
                ->assertExitCode(0);
            $this->assertSame(0, PlatformLocation::query()->where('external_id', '2490299')->firstOrFail()->catalog_priority);
        } finally {
            unlink($path);
        }
    }
}
