<?php

declare(strict_types=1);

use App\Filament\Widgets\ManagedEnvironment\ManagedEnvironmentVerificationReport;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Verification\VerificationReportWriter;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('renders the shared verification family on central operation detail', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $report = VerificationReportWriter::build('provider.connection.check', [
        [
            'key' => 'provider_connection',
            'title' => 'Provider connection preflight',
            'status' => 'fail',
            'severity' => 'critical',
            'blocking' => true,
            'reason_code' => 'provider_connection_missing',
            'message' => 'No provider connection configured.',
            'evidence' => [],
            'next_steps' => [],
        ],
    ]);

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'type' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'blocked',
        'context' => [
            'verification_report' => $report,
        ],
    ]);

    Filament::setTenant(null, true);

    $response = $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(\App\Support\OperationRunLinks::tenantlessView($run));

    $response->assertSuccessful()->assertSee('Verification report');

    expect($response->getContent())
        ->toContain('data-shared-detail-family="verification-report"')
        ->toContain('data-host-kind="operation_run_detail"')
        ->toContain('data-shared-zone="summary"')
        ->toContain('data-shared-zone="issues"')
        ->toContain('data-shared-zone="diagnostics"');
});

it('renders the shared verification family on onboarding verification', function (): void {
    $workspace = Workspace::factory()->create();
    $user = User::factory()->create();

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

    $tenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'status' => ManagedEnvironment::STATUS_ONBOARDING,
    ]);

    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);

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

    $report = VerificationReportWriter::build('provider.connection.check', [
        [
            'key' => 'onboarding_permissions',
            'title' => 'Graph permissions',
            'status' => 'fail',
            'severity' => 'high',
            'blocking' => false,
            'reason_code' => 'permission_denied',
            'message' => 'Missing required Graph permissions.',
            'evidence' => [],
            'next_steps' => [],
        ],
    ]);

    $run = OperationRun::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'managed_environment_id' => (int) $tenant->getKey(),
        'type' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'blocked',
        'context' => [
            'provider_connection_id' => (int) $connection->getKey(),
            'verification_report' => $report,
        ],
    ]);

    ManagedEnvironmentOnboardingSession::query()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'managed_environment_id' => (int) $tenant->getKey(),
        'entra_tenant_id' => (string) $tenant->managed_environment_id,
        'current_step' => 'verify',
        'state' => [
            'provider_connection_id' => (int) $connection->getKey(),
            'verification_operation_run_id' => (int) $run->getKey(),
        ],
        'started_by_user_id' => (int) $user->getKey(),
        'updated_by_user_id' => (int) $user->getKey(),
    ]);

    $response = $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->followingRedirects()
        ->get('/admin/onboarding');

    $response->assertSuccessful()->assertSee('Graph permissions');

    expect($response->getContent())
        ->toContain('data-shared-detail-family="verification-report"')
        ->toContain('data-host-kind="onboarding_wizard"')
        ->toContain('data-shared-zone="summary"')
        ->toContain('data-shared-zone="issues"')
        ->not->toContain('data-shared-zone="diagnostics"');
});

it('renders the shared verification family on the tenant widget host', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    Filament::setTenant($tenant, true);

    $report = VerificationReportWriter::build('provider.connection.check', [
        [
            'key' => 'tenant_widget_report',
            'title' => 'ManagedEnvironment widget verification',
            'status' => 'fail',
            'severity' => 'high',
            'blocking' => false,
            'reason_code' => 'provider_permission_denied',
            'message' => 'Insufficient permission — ask a tenant Owner.',
            'evidence' => [],
            'next_steps' => [],
        ],
    ]);

    OperationRun::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'type' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'blocked',
        'context' => [
            'target_scope' => [
                'entra_tenant_id' => (string) $tenant->managed_environment_id,
            ],
            'verification_report' => $report,
        ],
    ]);

    $component = Livewire::actingAs($user)
        ->test(ManagedEnvironmentVerificationReport::class, ['record' => $tenant])
        ->assertSee('ManagedEnvironment widget verification');

    expect($component->html())
        ->toContain('data-shared-detail-family="verification-report"')
        ->toContain('data-host-kind="tenant_widget"')
        ->toContain('data-shared-zone="summary"')
        ->toContain('data-shared-zone="issues"')
        ->toContain('data-shared-zone="diagnostics"');
});
