<?php

declare(strict_types=1);

use App\Filament\Pages\Reviews\CustomerReviewWorkspace;
use App\Filament\Resources\EnvironmentReviewResource;
use App\Filament\Resources\EnvironmentReviewResource\Pages\ViewEnvironmentReview;
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\App;
use Illuminate\Support\Facades\Storage;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('renders the customer review workspace in german for the effective locale', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['name' => 'Lokalisierter ManagedEnvironment']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');
    $user->forceFill(['preferred_locale' => 'de'])->save();

    $snapshot = seedEnvironmentReviewEvidence($tenant);

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

    App::setLocale('de');

    $this->actingAs($user);
    setAdminPanelContext();
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    Livewire::actingAs($user)
        ->test(CustomerReviewWorkspace::class)
        ->assertCanSeeTableRecords([$tenant->fresh()])
        ->assertSee('Kundensicherer Governance-Paket-Index')
        ->assertSee('Prüfen Sie für jeden berechtigten ManagedEnvironment den executive-fähigen Status des Governance-Pakets und öffnen Sie bei Bedarf die kundensichere Detailansicht.')
        ->assertSee('Jede Zeile ist ein Einstieg in die Detailansicht: Dort sehen Sie Paketstatus, Executive-Einstieg, Nachweise, aktuelle Risiken und den nächsten kundensicheren Schritt.')
        ->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('Governance-Paket')
        ->assertSee('Nachweise')
        ->assertSee('Nächster Schritt')
        ->assertSee('Review öffnen')
        ->assertDontSee('Customer-safe governance package index');
});

it('renders the customer review detail surface in german for the effective locale', function (): void {
    Storage::fake('exports');

    $tenant = ManagedEnvironment::factory()->create(['name' => 'Lokalisierter Detail-ManagedEnvironment']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');
    $user->forceFill(['preferred_locale' => 'de'])->save();

    $snapshot = seedEnvironmentReviewEvidence($tenant);

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

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

    $pack = ReviewPack::factory()->ready()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'environment_review_id' => (int) $review->getKey(),
        'evidence_snapshot_id' => (int) $snapshot->getKey(),
        'initiated_by_user_id' => (int) $user->getKey(),
        'file_path' => 'review-packs/customer-review-localization-test.zip',
        'file_disk' => 'exports',
    ]);

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

    App::setLocale('de');
    setAdminEnvironmentContext($tenant);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review], $tenant).'?'.http_build_query([
            CustomerReviewWorkspace::DETAIL_CONTEXT_QUERY_KEY => 1,
        ]))
        ->assertOk()
        ->assertSee('Veröffentlichter Governance-Nachweis')
        ->assertSee('Primäre Aktion')
        ->assertSee('Executive-Einstieg')
        ->assertSee('Strukturierter Auditor-Anhang')
        ->assertDontSee('Released governance record');

    $component = localizedEnvironmentReviewComponent($user, $review->getKey());

    $component->assertActionExists(
        'download_current_review_pack',
        fn (\Filament\Actions\Action $action): bool => $action->getLabel() === 'Governance-Paket herunterladen',
    );
});

function localizedEnvironmentReviewComponent($user, int $reviewId): Testable
{
    return Livewire::withQueryParams([CustomerReviewWorkspace::DETAIL_CONTEXT_QUERY_KEY => 1])
        ->actingAs($user)
        ->test(ViewEnvironmentReview::class, ['record' => $reviewId]);
}
