<?php

declare(strict_types=1);

use App\Filament\Resources\EnvironmentReviewResource;
use App\Models\ManagedEnvironment;
use App\Models\ReviewPack;
use App\Support\EnvironmentReviewStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;

uses(RefreshDatabase::class);

pest()->browser()->timeout(20_000);

beforeEach(function (): void {
    Storage::fake('exports');
});

it('smokes the customer review workspace handoff from environment review detail', function (): void {
    $tenantPublished = ManagedEnvironment::factory()->create(['name' => 'Published ManagedEnvironment']);
    [$user, $tenantPublished] = createUserWithTenant(
        tenant: $tenantPublished,
        role: 'owner',
        workspaceRole: 'manager',
    );
    $user->forceFill(['preferred_locale' => 'de'])->save();

    $tenantWithoutPublished = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenantPublished->workspace_id,
        'name' => 'No Published ManagedEnvironment',
    ]);

    createUserWithTenant(
        tenant: $tenantWithoutPublished,
        user: $user,
        role: 'owner',
        workspaceRole: 'manager',
    );

    $publishedSnapshot = seedEnvironmentReviewEvidence($tenantPublished);
    $noPublishedSnapshot = seedEnvironmentReviewEvidence($tenantWithoutPublished);

    $publishedReview = composeEnvironmentReviewForTest($tenantPublished, $user, $publishedSnapshot);
    $publishedReview->forceFill([
        'status' => EnvironmentReviewStatus::Published->value,
        'published_at' => now(),
        'published_by_user_id' => (int) $user->getKey(),
    ])->save();

    $internalOnlyReview = composeEnvironmentReviewForTest($tenantWithoutPublished, $user, $noPublishedSnapshot);
    $internalOnlyReview->forceFill([
        'status' => EnvironmentReviewStatus::Ready->value,
        'published_at' => null,
        'published_by_user_id' => null,
    ])->save();

    Storage::disk('exports')->put('review-packs/customer-review-workspace-smoke.zip', 'PK-test');

    $pack = ReviewPack::factory()->ready()->create([
        'managed_environment_id' => (int) $tenantPublished->getKey(),
        'workspace_id' => (int) $tenantPublished->workspace_id,
        'environment_review_id' => (int) $publishedReview->getKey(),
        'evidence_snapshot_id' => (int) $publishedSnapshot->getKey(),
        'initiated_by_user_id' => (int) $user->getKey(),
        'file_path' => 'review-packs/customer-review-workspace-smoke.zip',
        'file_disk' => 'exports',
    ]);

    $publishedReview->forceFill(['current_export_review_pack_id' => (int) $pack->getKey()])->save();

    $this->actingAs($user)->withSession([
        WorkspaceContext::SESSION_KEY => (int) $tenantPublished->workspace_id,
        WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
            (string) $tenantPublished->workspace_id => (int) $tenantPublished->getKey(),
        ],
    ]);

    visit(EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $publishedReview], $tenantPublished))
        ->waitForText('Verwandter Kontext')
        ->assertSee('Kunden-Workspace öffnen')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs()
        ->click('Kunden-Workspace öffnen')
        ->waitForText('Kundensicherer Governance-Paket-Index')
        ->assertSee('Filter löschen')
        ->assertSee('Review öffnen')
        ->assertSee('Governance-Paket')
        ->assertSee('Status')
        ->assertSee('Nachweise')
        ->assertSee('Prüfen Sie für jeden berechtigten ManagedEnvironment den executive-fähigen Status des Governance-Pakets')
        ->assertSee('Dieser Workspace fasst die aktuelle Review- und Nachweislage für die Service-Auslieferung zusammen. Er ersetzt weder ein formales Auditurteil noch eine Zertifizierung oder rechtliche Attestierung.')
        ->assertSee('Letztes veröffentlichtes Review')
        ->assertSee('Review-Pack herunterladen')
        ->assertSee('Das aktuelle Review-Pack ist zum Download bereit.')
        ->assertSee('Keine Entscheidungen mit Aufmerksamkeitsbedarf')
        ->assertSee('Zur Veröffentlichung bereit')
        ->assertSee('Verfügbar')
        ->assertDontSee('Customer-safe governance package index')
        ->assertDontSee('localization.review.customer_safe_review_workspace')
        ->assertDontSee('Publishable')
        ->assertDontSee('No mapped controls')
        ->assertDontSee('Compliance evidence mapping v1')
        ->assertDontSee('Publish review')
        ->assertDontSee('Refresh review')
        ->click('Filter löschen')
        ->waitForText('Published ManagedEnvironment')
        ->assertDontSee('No Published ManagedEnvironment')
        ->assertDontSee('No published review available yet')
        ->assertSeeIn('tbody tr.fi-ta-row:first-of-type td:last-child', 'Review öffnen')
        ->click('tbody tr.fi-ta-row:first-of-type td:last-child a')
        ->waitForText('Ergebniszusammenfassung')
        ->assertSee('Governance-Paket herunterladen')
        ->assertSee('Governance-Paket')
        ->assertSee('Veröffentlichter Governance-Nachweis')
        ->assertSee('Review-Status')
        ->assertSee('Primäre Aktion')
        ->assertSee('Executive-Einstieg')
        ->assertSee('Strukturierter Auditor-Anhang')
        ->assertSee('Prüfgrundlage')
        ->assertDontSee('Released governance record')
        ->assertDontSee('Control readiness interpretation')
        ->assertDontSee('Compliance evidence mapping v1')
        ->assertDontSee('Publish review')
        ->assertDontSee('Refresh review')
        ->assertDontSee('Create next review')
        ->assertDontSee('Export executive pack')
        ->assertDontSee('Archive review')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();
});
