<?php

declare(strict_types=1);

use App\Filament\Pages\InventoryCoverage;
use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Support\Badges\BadgeCatalog;
use App\Support\Badges\BadgeDomain;
use App\Support\Inventory\InventoryCoverage as InventoryCoveragePayload;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

function seedInventoryCoverageParityRun(ManagedEnvironment $tenant, string $status, int $itemCount): OperationRun
{
    return OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'inventory_sync',
        'status' => 'completed',
        'outcome' => $status === InventoryCoveragePayload::StatusSucceeded ? 'succeeded' : 'failed',
        'context' => [
            'inventory' => [
                'coverage' => InventoryCoveragePayload::buildPayload([
                    'deviceConfiguration' => [
                        'status' => $status,
                        'item_count' => $itemCount,
                        ...($status === InventoryCoveragePayload::StatusFailed ? ['error_code' => 'graph_forbidden'] : []),
                    ],
                ], []),
            ],
        ],
        'completed_at' => now(),
    ]);
}

it('loads inventory coverage from the remembered canonical tenant in the admin panel', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');
    $tenantB = ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenantA->workspace_id]);
    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $runA = seedInventoryCoverageParityRun($tenantA, InventoryCoveragePayload::StatusFailed, 0);
    $runB = seedInventoryCoverageParityRun($tenantB, InventoryCoveragePayload::StatusSucceeded, 1);

    $this->actingAs($user);
    Filament::setCurrentPanel('admin');
    Filament::setTenant(null, true);
    Filament::bootCurrentPanel();

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $tenantA->workspace_id => (int) $tenantA->getKey(),
    ]);

    Livewire::actingAs($user)->test(InventoryCoverage::class)
        ->assertOk()
        ->assertSee('ManagedEnvironment coverage truth')
        ->assertTableColumnFormattedStateSet(
            'coverage_state',
            BadgeCatalog::spec(BadgeDomain::InventoryCoverageState, 'failed')->label,
            'policy:deviceConfiguration',
        );
});

it('generates the canonical workspace environment inventory coverage URL', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $url = InventoryCoverage::getUrl(panel: 'admin', tenant: $tenant);
    $path = (string) parse_url($url, PHP_URL_PATH);

    expect($path)
        ->toBe(sprintf(
            '/admin/workspaces/%s/environments/%s/inventory/inventory-coverage',
            (string) $tenant->workspace_id,
            (string) $tenant->getRouteKey(),
        ))
        ->and($path)->not->toContain('/admin/t/')
        ->and($path)->not->toBe('/admin/inventory/inventory-coverage');
});

it('loads inventory coverage from the canonical environment route before remembered context', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');
    $tenantB = ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenantA->workspace_id]);
    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $runA = seedInventoryCoverageParityRun($tenantA, InventoryCoveragePayload::StatusFailed, 0);
    $runB = seedInventoryCoverageParityRun($tenantB, InventoryCoveragePayload::StatusSucceeded, 1);

    $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
            WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
                (string) $tenantA->workspace_id => (int) $tenantB->getKey(),
            ],
        ])
        ->get(InventoryCoverage::getUrl(panel: 'admin', tenant: $tenantA))
        ->assertOk()
        ->assertSee(BadgeCatalog::spec(BadgeDomain::InventoryCoverageState, 'failed')->label)
        ->assertSee(OperationRunLinks::view($runA, $tenantA), false)
        ->assertDontSee(OperationRunLinks::view($runB, $tenantB), false);
});
