<?php

declare(strict_types=1);

use App\Http\Middleware\ForumBotProtectionMiddleware;
use App\Models\Country;
use App\Models\User;

it('stores a selected country on the personal settings endpoint', function (): void {
    $this->withoutMiddleware(ForumBotProtectionMiddleware::class);

    $user = User::factory()->create();
    $country = Country::query()->where('iso2', 'SI')->firstOrFail();
    $country->update([
        'iso' => 'SI',
        'iso3' => 'SVN',
        'name' => 'Slovenia',
        'name_common' => 'Slovenia',
    ]);

    $response = $this->actingAs($user)->postJson('/settings/personal/update', [
        'birthday' => '1990-01-02',
        'gender' => 'm',
        'country_id' => $country->id,
    ]);

    $response->assertOk();

    $user->refresh();

    expect($user->country_id)->toBe($country->id);
    expect(optional($user->profile)->country_code)->toBe('SI');
});

it('rejects invalid country identifiers on the personal settings endpoint', function (): void {
    $this->withoutMiddleware(ForumBotProtectionMiddleware::class);

    $user = User::factory()->create();

    $response = $this->actingAs($user)->postJson('/settings/personal/update', [
        'country_id' => 999999,
    ]);

    $response->assertStatus(422)
        ->assertJsonValidationErrors(['country_id']);
});

it('loads countries on the dashboard profile settings page', function (): void {
    $this->withoutMiddleware(ForumBotProtectionMiddleware::class);

    $user = User::factory()->create();
    Country::query()->where('iso2', 'SI')->update([
        'iso' => 'SI',
        'iso3' => 'SVN',
        'name' => 'Slovenia',
        'name_common' => 'Slovenia',
        'flag_emoji' => '🇸🇮',
    ]);

    $response = $this->actingAs($user)->get('/dashboard/profile');

    $response->assertOk()->assertSee('Slovenia');
});

it('supports country persistence through the legacy profile update endpoint', function (): void {
    $user = User::factory()->create();
    $country = Country::query()->where('iso2', 'DE')->firstOrFail();
    $country->update([
        'iso' => 'DE',
        'iso3' => 'DEU',
        'name' => 'Germany',
        'name_common' => 'Germany',
    ]);

    $response = $this->actingAs($user)
        ->from('/profile/edit')
        ->patch('/profile', [
            'name' => 'Updated User',
            'email' => $user->email,
            'country_id' => $country->id,
        ]);

    $response->assertSessionHasNoErrors();
    expect($user->fresh()->country_id)->toBe($country->id);
    expect(optional($user->fresh()->profile)->country_code)->toBe('DE');
});
