<?php

namespace Tests\Feature;

use App\Models\Setting;
use App\Models\User;
use Database\Seeders\CcliSettingsSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

/**
 * @mixin \Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication
 * @mixin \Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase
 */
final class SettingsDefaultLanguageTest extends TestCase
{
    use RefreshDatabase;

    public function test_default_translation_language_is_seeded_with_de(): void
    {
        $this->seed(CcliSettingsSeeder::class);

        $setting = Setting::where('key', 'default_translation_language')->first();

        $this->assertNotNull($setting);
        $this->assertSame('DE', $setting?->value);
    }

    #[DataProvider('validLanguages')]
    public function test_accepts_valid_default_translation_language_via_patch(string $language): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->patchJson(route('settings.update'), [
            'key' => 'default_translation_language',
            'value' => $language,
        ]);

        $response->assertOk()->assertJson(['success' => true]);

        $this->assertSame($language, Setting::get('default_translation_language'));
    }

    public static function validLanguages(): array
    {
        return [
            ['DE'],
            ['EN'],
            ['FR'],
            ['ES'],
            ['NL'],
            ['IT'],
        ];
    }

    public function test_rejects_invalid_default_translation_language_via_patch(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->patchJson(route('settings.update'), [
            'key' => 'default_translation_language',
            'value' => 'ZZ',
        ]);

        $response->assertUnprocessable();
        $response->assertJsonValidationErrors('value');
    }

    public function test_exposes_default_translation_language_in_settings_props(): void
    {
        $user = User::factory()->create();

        $this->seed(CcliSettingsSeeder::class);

        $response = $this->actingAs($user)
            ->withoutVite()
            ->get(route('settings.index'));

        $response->assertInertia(
            fn ($page) => $page
                ->component('Settings')
                ->has('settings.default_translation_language')
                ->where('settings.default_translation_language', 'DE')
        );
    }
}
