<?php

declare(strict_types=1);

use App\Filament\Pages\Settings\WorkspaceSettings;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Settings\SettingsResolver;
use App\Support\Workspaces\WorkspaceContext;
use Livewire\Livewire;

/**
 * @return array{0: Workspace, 1: User}
 */
function workspaceAiPolicyManager(): array
{
    $workspace = Workspace::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'manager',
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());

    return [$workspace, $user];
}

it('renders the workspace ai policy section and lets managers save and reset the ai posture', function (): void {
    [$workspace, $user] = workspaceAiPolicyManager();

    $this->actingAs($user)
        ->get(WorkspaceSettings::getUrl(panel: 'admin'))
        ->assertSuccessful()
        ->assertSee('Workspace AI policy')
        ->assertSee('Disabled')
        ->assertSee('Private only')
        ->assertSee('Approved use cases')
        ->assertSee('Blocked data classifications');

    expect(app(SettingsResolver::class)->resolveValue($workspace, 'ai', 'policy_mode'))
        ->toBe('disabled');

    $component = Livewire::actingAs($user)
        ->test(WorkspaceSettings::class)
        ->assertSet('data.ai_policy_mode', null)
        ->set('data.ai_policy_mode', 'private_only')
        ->callAction('save')
        ->assertHasNoErrors()
        ->assertSet('data.ai_policy_mode', 'private_only');

    expect(app(SettingsResolver::class)->resolveValue($workspace, 'ai', 'policy_mode'))
        ->toBe('private_only');

    $component
        ->mountFormComponentAction('ai_policy_mode', 'reset_ai_policy_mode', [], 'content')
        ->callMountedFormComponentAction()
        ->assertHasNoErrors()
        ->assertSet('data.ai_policy_mode', null);

    expect(app(SettingsResolver::class)->resolveValue($workspace, 'ai', 'policy_mode'))
        ->toBe('disabled');
});