<?php

declare(strict_types=1);

use App\Models\Finding;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Models\OperationRun;
use App\Models\PlatformUser;
use App\Models\ProductUsageEvent;
use App\Models\ProviderConnection;
use App\Models\ReviewPack;
use App\Models\Workspace;
use App\Support\Auth\PlatformCapabilities;
use App\Support\CustomerHealth\CustomerHealthDimensionCatalog;
use App\Support\CustomerHealth\WorkspaceHealthSummaryQuery;
use App\Support\Onboarding\OnboardingLifecycleState;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\ProductTelemetry\ProductUsageEventCatalog;
use App\Support\Providers\ProviderConsentStatus;
use App\Support\Providers\ProviderVerificationStatus;
use App\Support\System\SystemDirectoryLinks;
use App\Support\System\SystemOperationRunLinks;
use App\Support\SystemConsole\SystemConsoleWindow;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    CarbonImmutable::setTestNow(CarbonImmutable::parse('2025-02-15 12:00:00'));
});

afterEach(function (): void {
    CarbonImmutable::setTestNow();
});

it('derives workspace health from existing onboarding, provider, and telemetry truth', function (): void {
    $workspace = Workspace::factory()->create(['name' => 'Acme']);
    $tenant = ManagedEnvironment::factory()->for($workspace)->create([
        'name' => 'Acme Production',
        'status' => ManagedEnvironment::STATUS_ACTIVE,
    ]);

    ProviderConnection::factory()
        ->for($tenant)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'is_default' => true,
            'is_enabled' => true,
            'consent_status' => ProviderConsentStatus::Granted->value,
            'verification_status' => ProviderVerificationStatus::Blocked->value,
        ]);

    ProductUsageEvent::factory()
        ->for($tenant)
        ->forEvent(ProductUsageEventCatalog::ONBOARDING_CHECKPOINT_COMPLETED)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'occurred_at' => now()->subHours(2),
        ]);

    Finding::factory()
        ->for($tenant)
        ->closed()
        ->create([
            'severity' => Finding::SEVERITY_LOW,
        ]);

    $summary = summaryForWorkspace($workspace);

    expect($summary['overall_level'])->toBe('critical')
        ->and($summary['dimensions'][CustomerHealthDimensionCatalog::ONBOARDING_READINESS]['level'])->toBe('ok')
        ->and($summary['dimensions'][CustomerHealthDimensionCatalog::PROVIDER_CONNECTION_HEALTH]['level'])->toBe('critical')
        ->and($summary['dimensions'][CustomerHealthDimensionCatalog::ENGAGEMENT_FRESHNESS]['level'])->toBe('ok')
        ->and($summary['dominant_dimension_keys'])->toBe([CustomerHealthDimensionCatalog::PROVIDER_CONNECTION_HEALTH, CustomerHealthDimensionCatalog::OPERATIONAL_STABILITY, CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS])
        ->and($summary['next_link'])->toBe([
            'label' => 'Review health details',
            'url' => SystemDirectoryLinks::tenantDetail($tenant).'?window='.SystemConsoleWindow::LastDay,
        ]);
});

it('applies the selected window review-pack readiness rules', function (): void {
    $unknownWorkspace = createWorkspaceWithActiveTenant('Unknown Workspace');
    $warnWorkspace = createWorkspaceWithActiveTenant('Warn Workspace');
    $okWorkspace = createWorkspaceWithActiveTenant('Ok Workspace');
    $criticalWorkspace = createWorkspaceWithActiveTenant('Critical Workspace');

    ProductUsageEvent::factory()
        ->for($warnWorkspace['tenant'])
        ->forEvent(ProductUsageEventCatalog::REVIEW_PACK_REQUESTED)
        ->create([
            'workspace_id' => (int) $warnWorkspace['workspace']->getKey(),
            'occurred_at' => now()->subHours(1),
        ]);

    ReviewPack::factory()
        ->for($okWorkspace['tenant'])
        ->ready()
        ->create([
            'workspace_id' => (int) $okWorkspace['workspace']->getKey(),
            'created_at' => now()->subHours(3),
            'generated_at' => now()->subHours(2),
            'expires_at' => now()->addDays(30),
        ]);

    ReviewPack::factory()
        ->for($criticalWorkspace['tenant'])
        ->failed()
        ->create([
            'workspace_id' => (int) $criticalWorkspace['workspace']->getKey(),
            'created_at' => now()->subHours(2),
        ]);

    $summaries = app(WorkspaceHealthSummaryQuery::class)
        ->summaries(SystemConsoleWindow::LastDay)
        ->keyBy('workspace_id');

    expect($summaries[(int) $unknownWorkspace['workspace']->getKey()]['dimensions'][CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS]['level'])->toBe('unknown')
        ->and($summaries[(int) $warnWorkspace['workspace']->getKey()]['dimensions'][CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS]['level'])->toBe('warn')
        ->and($summaries[(int) $okWorkspace['workspace']->getKey()]['dimensions'][CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS]['level'])->toBe('ok')
        ->and($summaries[(int) $criticalWorkspace['workspace']->getKey()]['dimensions'][CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS]['level'])->toBe('critical');
});

it('uses the selected window for operations and engagement freshness', function (): void {
    $workspace = Workspace::factory()->create(['name' => 'Windowed Signals']);
    $tenant = ManagedEnvironment::factory()->for($workspace)->create([
        'status' => ManagedEnvironment::STATUS_ACTIVE,
        'name' => 'Windowed ManagedEnvironment',
    ]);

    ProviderConnection::factory()
        ->for($tenant)
        ->verifiedHealthy()
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'is_default' => true,
        ]);

    ProductUsageEvent::factory()
        ->for($tenant)
        ->forEvent(ProductUsageEventCatalog::ONBOARDING_CHECKPOINT_COMPLETED)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'occurred_at' => now()->subDays(3),
        ]);

    OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Failed->value,
            'created_at' => now()->subDays(2),
            'started_at' => now()->subDays(2)->subMinutes(5),
            'completed_at' => now()->subDays(2),
        ]);

    $summary = summaryForWorkspace($workspace);

    expect($summary['dimensions'][CustomerHealthDimensionCatalog::ENGAGEMENT_FRESHNESS]['level'])->toBe('warn')
        ->and($summary['dimensions'][CustomerHealthDimensionCatalog::OPERATIONAL_STABILITY]['level'])->toBe('unknown');
});

it('keeps governance pressure explicit until governance truth exists', function (): void {
    $workspace = Workspace::factory()->create(['name' => 'Governance Signals']);
    $tenant = ManagedEnvironment::factory()->for($workspace)->create([
        'status' => ManagedEnvironment::STATUS_ACTIVE,
        'name' => 'Governance ManagedEnvironment',
    ]);

    ProviderConnection::factory()
        ->for($tenant)
        ->verifiedHealthy()
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'is_default' => true,
        ]);

    ReviewPack::factory()
        ->for($tenant)
        ->ready()
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'created_at' => now()->subHour(),
            'generated_at' => now()->subHour(),
            'expires_at' => now()->addDays(30),
        ]);

    ProductUsageEvent::factory()
        ->for($tenant)
        ->forEvent(ProductUsageEventCatalog::ONBOARDING_CHECKPOINT_COMPLETED)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'occurred_at' => now()->subMinutes(20),
        ]);

    OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Succeeded->value,
            'created_at' => now()->subMinutes(10),
            'started_at' => now()->subMinutes(15),
            'completed_at' => now()->subMinutes(5),
        ]);

    $summaryWithoutGovernanceTruth = summaryForWorkspace($workspace);

    expect($summaryWithoutGovernanceTruth['dimensions'][CustomerHealthDimensionCatalog::GOVERNANCE_PRESSURE]['level'])->toBe('unknown');

    Finding::factory()
        ->for($tenant)
        ->closed()
        ->create([
            'severity' => Finding::SEVERITY_LOW,
        ]);

    $summaryWithGovernanceTruth = summaryForWorkspace($workspace);

    expect($summaryWithGovernanceTruth['dimensions'][CustomerHealthDimensionCatalog::GOVERNANCE_PRESSURE]['level'])->toBe('ok');
});

it('ignores archived workspaces and archived tenant truth for active workspace summaries', function (): void {
    $archivedWorkspace = Workspace::factory()->create([
        'name' => 'Archived Workspace',
        'archived_at' => now()->subDay(),
    ]);

    $archivedWorkspaceTenant = ManagedEnvironment::factory()->for($archivedWorkspace)->create([
        'status' => ManagedEnvironment::STATUS_ACTIVE,
    ]);

    ProductUsageEvent::factory()
        ->for($archivedWorkspaceTenant)
        ->create([
            'workspace_id' => (int) $archivedWorkspace->getKey(),
            'occurred_at' => now()->subHour(),
        ]);

    $workspace = Workspace::factory()->create(['name' => 'Mixed Workspace']);
    $activeEnvironment = ManagedEnvironment::factory()->for($workspace)->create([
        'status' => ManagedEnvironment::STATUS_ACTIVE,
        'name' => 'Active ManagedEnvironment',
    ]);

    $archivedTenant = ManagedEnvironment::factory()->for($workspace)->create([
        'status' => ManagedEnvironment::STATUS_ARCHIVED,
        'name' => 'Archived ManagedEnvironment',
        'deleted_at' => now()->subDay(),
    ]);

    ProviderConnection::factory()
        ->for($activeEnvironment)
        ->verifiedHealthy()
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'is_default' => true,
        ]);

    ProviderConnection::factory()
        ->for($archivedTenant)
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'is_default' => true,
            'is_enabled' => true,
            'consent_status' => ProviderConsentStatus::Granted->value,
            'verification_status' => ProviderVerificationStatus::Blocked->value,
        ]);

    $summaries = app(WorkspaceHealthSummaryQuery::class)->summaries();
    $summary = $summaries->firstWhere('workspace_id', (int) $workspace->getKey());

    expect($summaries->contains(fn (array $item): bool => $item['workspace_id'] === (int) $archivedWorkspace->getKey()))->toBeFalse()
        ->and($summary)->not->toBeNull()
        ->and($summary['dimensions'][CustomerHealthDimensionCatalog::PROVIDER_CONNECTION_HEALTH]['level'])->toBe('ok');
});

it('sorts the attention list by severity, breadth, and name', function (): void {
    $platformUser = PlatformUser::factory()->create([
        'capabilities' => [
            PlatformCapabilities::ACCESS_SYSTEM_PANEL,
            PlatformCapabilities::CONSOLE_VIEW,
            PlatformCapabilities::OPERATIONS_VIEW,
        ],
        'is_active' => true,
    ]);

    $this->actingAs($platformUser, 'platform');

    $criticalWorkspace = Workspace::factory()->create(['name' => 'Critical Workspace']);
    $criticalTenant = ManagedEnvironment::factory()->for($criticalWorkspace)->create([
        'status' => ManagedEnvironment::STATUS_ACTIVE,
        'name' => 'Critical ManagedEnvironment',
    ]);

    ProviderConnection::factory()
        ->for($criticalTenant)
        ->verifiedHealthy()
        ->create([
            'workspace_id' => (int) $criticalWorkspace->getKey(),
            'is_default' => true,
        ]);

    OperationRun::factory()
        ->forTenant($criticalTenant)
        ->create([
            'workspace_id' => (int) $criticalWorkspace->getKey(),
            'status' => OperationRunStatus::Queued->value,
            'outcome' => OperationRunOutcome::Pending->value,
            'created_at' => now()->subHours(2),
            'started_at' => null,
        ]);

    $warnWorkspace = Workspace::factory()->create(['name' => 'Warn Workspace']);
    $warnTenant = ManagedEnvironment::factory()->for($warnWorkspace)->create([
        'status' => ManagedEnvironment::STATUS_ACTIVE,
        'name' => 'Warn ManagedEnvironment',
    ]);

    ProviderConnection::factory()
        ->for($warnTenant)
        ->verifiedHealthy()
        ->create([
            'workspace_id' => (int) $warnWorkspace->getKey(),
            'is_default' => true,
        ]);

    ProductUsageEvent::factory()
        ->for($warnTenant)
        ->forEvent(ProductUsageEventCatalog::ONBOARDING_CHECKPOINT_COMPLETED)
        ->create([
            'workspace_id' => (int) $warnWorkspace->getKey(),
            'occurred_at' => now()->subDays(5),
        ]);

    $unknownWorkspace = Workspace::factory()->create(['name' => 'Unknown Workspace']);

    ManagedEnvironmentOnboardingSession::factory()
        ->forWorkspace($unknownWorkspace)
        ->create([
            'lifecycle_state' => OnboardingLifecycleState::Draft->value,
        ]);

    $attention = app(WorkspaceHealthSummaryQuery::class)
        ->attentionNeeded(SystemConsoleWindow::LastDay, 3)
        ->values();

    expect($attention->pluck('workspace_name')->all())->toBe([
        'Critical Workspace',
        'Unknown Workspace',
        'Warn Workspace',
    ])
        ->and($attention[0]['next_link'])->toBe([
            'label' => 'Open runs',
            'url' => SystemOperationRunLinks::index(),
        ]);
});

/**
 * @return array{workspace: Workspace, tenant: ManagedEnvironment}
 */
function createWorkspaceWithActiveTenant(string $workspaceName): array
{
    $workspace = Workspace::factory()->create(['name' => $workspaceName]);
    $tenant = ManagedEnvironment::factory()->for($workspace)->create([
        'name' => $workspaceName.' ManagedEnvironment',
        'status' => ManagedEnvironment::STATUS_ACTIVE,
    ]);

    ProviderConnection::factory()
        ->for($tenant)
        ->verifiedHealthy()
        ->create([
            'workspace_id' => (int) $workspace->getKey(),
            'is_default' => true,
        ]);

    return [
        'workspace' => $workspace,
        'tenant' => $tenant,
    ];
}

/**
 * @return array{
 *     workspace_id: int,
 *     workspace_name: string,
 *     overall_level: string,
 *     dimensions: array<string, array{label: string, level: string, windowed: bool}>,
 *     dominant_dimension_keys: list<string>,
 *     non_ok_dimension_count: int,
 *     next_link: array{label: string, url: string}
 * }
 */
function summaryForWorkspace(Workspace $workspace): array
{
    /** @var array{
     *     workspace_id: int,
     *     workspace_name: string,
     *     overall_level: string,
     *     dimensions: array<string, array{label: string, level: string, windowed: bool}>,
     *     dominant_dimension_keys: list<string>,
     *     non_ok_dimension_count: int,
     *     next_link: array{label: string, url: string}
     * } $summary
     */
    $summary = app(WorkspaceHealthSummaryQuery::class)
        ->summaryForWorkspace($workspace, SystemConsoleWindow::LastDay);

    return $summary;
}
