<?php

declare(strict_types=1);

use App\Filament\Widgets\Dashboard\BaselineCompareNow;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineTenantAssignment;
use App\Models\OperationRun;
use App\Support\Baselines\BaselineCompareReasonCode;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use Filament\Facades\Filament;
use Livewire\Livewire;

function createBaselineCompareWidgetTenant(): array
{
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'name' => 'Baseline A',
    ]);

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    return [$user, $tenant, $profile, $snapshot];
}

it('renders a trustworthy no-drift dashboard summary without compliance shorthand', function (): void {
    [$user, $tenant, $profile, $snapshot] = createBaselineCompareWidgetTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::NoDriftDetected->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => [],
                    'proof' => true,
                ],
            ],
        ],
        'completed_at' => now()->subDay(),
    ]);

    $this->actingAs($user);

    setAdminPanelContext($tenant);

    Livewire::test(BaselineCompareNow::class)
        ->assertSee('Baseline Governance')
        ->assertSee('Baseline A')
        ->assertSee('Aligned')
        ->assertSee('No confirmed drift in the latest baseline compare.')
        ->assertSee('No action needed')
        ->assertDontSee('baseline compliant');
});

it('renders limited-confidence zero findings as a cautionary widget state', function (): void {
    [$user, $tenant, $profile, $snapshot] = createBaselineCompareWidgetTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::PartiallySucceeded->value,
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'baseline_compare' => [
                'reason_code' => BaselineCompareReasonCode::CoverageUnproven->value,
                'coverage' => [
                    'effective_types' => ['deviceConfiguration', 'deviceCompliancePolicy'],
                    'covered_types' => ['deviceConfiguration'],
                    'uncovered_types' => ['deviceCompliancePolicy'],
                    'proof' => false,
                ],
                'evidence_gaps' => [
                    'count' => 2,
                    'by_reason' => [
                        BaselineCompareReasonCode::CoverageUnproven->value => 2,
                    ],
                ],
            ],
        ],
        'completed_at' => now(),
    ]);

    $this->actingAs($user);

    setAdminPanelContext($tenant);

    Livewire::test(BaselineCompareNow::class)
        ->assertSee('Needs review')
        ->assertSee('The last compare finished, but normal result output was suppressed.')
        ->assertSee('Review compare detail')
        ->assertDontSee('Aligned')
        ->assertDontSee('baseline compliant');
});

it('renders failed compare runs as action required with a run drilldown', function (): void {
    [$user, $tenant, $profile, $snapshot] = createBaselineCompareWidgetTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
        ],
        'failure_summary' => ['message' => 'Graph API timeout'],
        'completed_at' => now()->subMinutes(30),
    ]);

    $this->actingAs($user);

    setAdminPanelContext($tenant);

    Livewire::test(BaselineCompareNow::class)
        ->assertSee('Action required')
        ->assertSee('The latest baseline compare failed before it produced a usable result.')
        ->assertSee('Review the failed operation')
        ->assertDontSee('Aligned');
});

it('renders in-progress compare runs without claiming an all-clear', function (): void {
    [$user, $tenant, $profile, $snapshot] = createBaselineCompareWidgetTenant();

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Queued->value,
        'outcome' => OperationRunOutcome::Pending->value,
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
        ],
    ]);

    $this->actingAs($user);

    setAdminPanelContext($tenant);

    Livewire::test(BaselineCompareNow::class)
        ->assertSee('In progress')
        ->assertSee('Baseline compare is in progress.')
        ->assertSee('Open operation')
        ->assertDontSee('Aligned');
});

it('renders snapshot-unavailable posture as unavailable rather than healthy', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'name' => 'Baseline A',
        'active_snapshot_id' => null,
    ]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    $this->actingAs($user);

    setAdminPanelContext($tenant);

    Livewire::test(BaselineCompareNow::class)
        ->assertSee('Unavailable')
        ->assertSee('The current baseline snapshot is not available for compare.')
        ->assertSee('Review baseline prerequisites')
        ->assertDontSee('Aligned');
});
