<?php

declare(strict_types=1);

use App\Filament\Pages\Settings\WorkspaceSettings;
use App\Models\WorkspaceSetting;
use App\Services\Localization\LocaleResolver;
use App\Services\Settings\SettingsResolver;
use Livewire\Livewire;

it('persists workspace default locale through the existing workspace settings page', function (): void {
    [$workspace, $user] = localizationWorkspaceMember();

    $this->actingAs($user)
        ->get(WorkspaceSettings::getUrl(panel: 'admin'))
        ->assertSuccessful();

    Livewire::actingAs($user)
        ->test(WorkspaceSettings::class)
        ->assertSet('data.localization_default_locale', null)
        ->set('data.localization_default_locale', 'de')
        ->callAction('save')
        ->assertHasNoErrors()
        ->assertSet('data.localization_default_locale', 'de');

    expect(app(SettingsResolver::class)->resolveValue($workspace, LocaleResolver::SETTING_DOMAIN, LocaleResolver::SETTING_DEFAULT_LOCALE))
        ->toBe('de');

    expect(WorkspaceSetting::query()
        ->where('workspace_id', (int) $workspace->getKey())
        ->where('domain', LocaleResolver::SETTING_DOMAIN)
        ->where('key', LocaleResolver::SETTING_DEFAULT_LOCALE)
        ->exists())->toBeTrue();
});

it('keeps workspace default locale authorization aligned to settings capabilities', function (): void {
    [$workspace, $user] = localizationWorkspaceMember('readonly');

    $this->actingAs($user)
        ->get(WorkspaceSettings::getUrl(panel: 'admin'))
        ->assertSuccessful();

    Livewire::actingAs($user)
        ->test(WorkspaceSettings::class)
        ->assertSet('data.localization_default_locale', null)
        ->assertActionVisible('save')
        ->assertActionDisabled('save')
        ->call('save')
        ->assertStatus(403);
});
