<?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\Models\WorkspaceSubscription;
use App\Services\Entitlements\WorkspaceEntitlementResolver;
use App\Support\Workspaces\WorkspaceContext;
use Livewire\Livewire;

/**
 * @return array{0: Workspace, 1: User}
 */
function entitlementSettingsManager(): 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('saves entitlement plan profile and override pairs through the workspace settings page', function (): void {
    [$workspace, $user] = entitlementSettingsManager();

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

    $component = Livewire::actingAs($user)
        ->test(WorkspaceSettings::class)
        ->assertSet('data.entitlements_plan_profile', null)
        ->assertSet('data.entitlements_managed_tenant_limit_override_value', null)
        ->assertSet('data.entitlements_managed_tenant_limit_override_reason', null)
        ->assertSet('data.entitlements_review_pack_generation_override_value', null)
        ->assertSet('data.entitlements_review_pack_generation_override_reason', null)
        ->set('data.entitlements_plan_profile', 'starter')
        ->set('data.entitlements_managed_tenant_limit_override_value', 2)
        ->set('data.entitlements_managed_tenant_limit_override_reason', 'Temporary support-approved exception')
        ->set('data.entitlements_review_pack_generation_override_value', '0')
        ->set('data.entitlements_review_pack_generation_override_reason', 'Workspace is temporarily limited to manual reporting only')
        ->callAction('save')
        ->assertHasNoErrors()
        ->assertSet('data.entitlements_plan_profile', 'starter')
        ->assertSet('data.entitlements_managed_tenant_limit_override_value', 2)
        ->assertSet('data.entitlements_managed_tenant_limit_override_reason', 'Temporary support-approved exception')
        ->assertSet('data.entitlements_review_pack_generation_override_value', '0')
        ->assertSet('data.entitlements_review_pack_generation_override_reason', 'Workspace is temporarily limited to manual reporting only');

    $summary = app(WorkspaceEntitlementResolver::class)->summary($workspace);

    expect($summary['plan_profile']['id'])->toBe('starter')
        ->and($summary['decisions'][WorkspaceEntitlementResolver::KEY_MANAGED_TENANT_ACTIVATION_LIMIT])
        ->toMatchArray([
            'effective_value' => 2,
            'source' => 'workspace_override',
            'rationale' => 'Temporary support-approved exception',
            'last_changed_by' => $user->name,
        ])
        ->and($summary['decisions'][WorkspaceEntitlementResolver::KEY_REVIEW_PACK_GENERATION_ENABLED])
        ->toMatchArray([
            'effective_value' => false,
            'source' => 'workspace_override',
            'rationale' => 'Workspace is temporarily limited to manual reporting only',
            'last_changed_by' => $user->name,
        ]);

    $component
        ->mountFormComponentAction('entitlements_managed_tenant_limit_override_value', 'reset_entitlements_managed_tenant_limit_override_value', [], 'content')
        ->callMountedFormComponentAction()
        ->assertHasNoErrors()
        ->assertSet('data.entitlements_managed_tenant_limit_override_value', null)
        ->assertSet('data.entitlements_managed_tenant_limit_override_reason', null);

    $summary = app(WorkspaceEntitlementResolver::class)->summary($workspace);

    expect($summary['decisions'][WorkspaceEntitlementResolver::KEY_MANAGED_TENANT_ACTIVATION_LIMIT])
        ->toMatchArray([
            'effective_value' => 1,
            'source' => 'plan_profile_default',
            'rationale' => 'Minimal allowance for early workspace access and low-volume operations.',
        ]);
});

it('requires an override reason when a workspace entitlement override value is set', function (): void {
    [, $user] = entitlementSettingsManager();

    Livewire::actingAs($user)
        ->test(WorkspaceSettings::class)
        ->set('data.entitlements_managed_tenant_limit_override_value', 3)
        ->set('data.entitlements_managed_tenant_limit_override_reason', '')
        ->callAction('save')
        ->assertHasErrors(['data.entitlements_managed_tenant_limit_override_reason']);

    Livewire::actingAs($user)
        ->test(WorkspaceSettings::class)
        ->set('data.entitlements_review_pack_generation_override_value', '0')
        ->set('data.entitlements_review_pack_generation_override_reason', '')
        ->callAction('save')
        ->assertHasErrors(['data.entitlements_review_pack_generation_override_reason']);
});

it('shows a read-only subscription-backed commercial summary on workspace settings', function (): void {
    [$workspace, $user] = entitlementSettingsManager();
    $trialEndsAt = now()->addDays(14)->startOfMinute();

    WorkspaceSubscription::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'state' => 'trial',
        'billing_reference' => 'sub_trial_001',
        'trial_ends_at' => $trialEndsAt,
        'status_reason' => 'Trial access for onboarding.',
    ]);

    $this->actingAs($user)
        ->get(WorkspaceSettings::getUrl(panel: 'admin'))
        ->assertSuccessful()
        ->assertSee('Commercial posture')
        ->assertSee('subscription-backed')
        ->assertSee('Trial')
        ->assertSee('Trial access for onboarding.')
        ->assertSee('Trial ends')
        ->assertDontSee('Update subscription truth')
        ->assertDontSee('Change commercial state');
});