<?php

declare(strict_types=1);

use App\Models\Country;
use Illuminate\Support\Facades\Http;

it('sync command imports countries from the configured remote source', function (): void {
    config()->set('skinbase-countries.endpoint', 'https://countries.test/all');
    config()->set('skinbase-countries.fallback_seed_enabled', false);

    Http::fake([
        'https://countries.test/all' => Http::response([
            [
                'cca2' => 'SI',
                'cca3' => 'SVN',
                'ccn3' => '705',
                'name' => ['common' => 'Slovenia', 'official' => 'Republic of Slovenia'],
                'region' => 'Europe',
                'subregion' => 'Central Europe',
                'flags' => ['svg' => 'https://flags.test/si.svg', 'png' => 'https://flags.test/si.png'],
                'flag' => '🇸🇮',
            ],
        ], 200),
    ]);

    $this->artisan('skinbase:sync-countries')->assertSuccessful();

    expect(Country::query()->where('iso2', 'SI')->value('name_common'))->toBe('Slovenia');
});

it('sync command fails when the remote source errors and fallback is disabled', function (): void {
    config()->set('skinbase-countries.endpoint', 'https://countries.test/all');
    config()->set('skinbase-countries.fallback_seed_enabled', false);

    Http::fake([
        'https://countries.test/all' => Http::response(['message' => 'server error'], 500),
    ]);

    $this->artisan('skinbase:sync-countries')
        ->assertExitCode(1);
});

it('sync command fails gracefully when the payload contains no valid country records', function (): void {
    config()->set('skinbase-countries.endpoint', 'https://countries.test/all');
    config()->set('skinbase-countries.fallback_seed_enabled', false);

    Http::fake([
        'https://countries.test/all' => Http::response([
            ['bad' => 'payload'],
        ], 200),
    ]);

    $this->artisan('skinbase:sync-countries')
        ->assertExitCode(1);
});
