<?php

declare(strict_types=1);

use App\Filament\Resources\TenantReviewResource;
use App\Filament\Widgets\Tenant\TenantReviewPackCard;
use App\Jobs\GenerateReviewPackJob;
use App\Services\ReviewPackService;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;

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

it('renders an executive-ready tenant review and exports a pack with matching section order and summary truth', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $review = composeTenantReviewForTest($tenant, $user);

    $this->actingAs($user)
        ->get(TenantReviewResource::tenantScopedUrl('view', ['record' => $review], $tenant))
        ->assertOk()
        ->assertSee('Executive posture')
        ->assertSee('Executive summary')
        ->assertSee('Open risk highlights')
        ->assertSee('Permission posture')
        ->assertSee('Publication readiness');

    $pack = app(ReviewPackService::class)->generateFromReview($review, $user, [
        'include_pii' => true,
        'include_operations' => true,
    ]);

    $job = new GenerateReviewPackJob(
        reviewPackId: (int) $pack->getKey(),
        operationRunId: (int) $pack->operation_run_id,
    );
    app()->call([$job, 'handle']);

    $pack->refresh();
    $review->refresh()->load(['sections', 'evidenceSnapshot']);

    $zipContent = Storage::disk('exports')->get((string) $pack->file_path);
    $tempFile = tempnam(sys_get_temp_dir(), 'tenant-review-pack-');
    file_put_contents($tempFile, $zipContent);

    $zip = new ZipArchive;
    $zip->open($tempFile);

    $metadata = json_decode((string) $zip->getFromName('metadata.json'), true, 512, JSON_THROW_ON_ERROR);
    $summary = json_decode((string) $zip->getFromName('summary.json'), true, 512, JSON_THROW_ON_ERROR);
    $sections = json_decode((string) $zip->getFromName('sections.json'), true, 512, JSON_THROW_ON_ERROR);
    $executiveEntrypoint = (string) $zip->getFromName(ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME);
    $filenames = collect(range(0, $zip->numFiles - 1))
        ->map(fn (int $index): string => (string) $zip->getNameIndex($index))
        ->values()
        ->all();

    expect(array_column($sections, 'section_key'))
        ->toBe($review->sections->pluck('section_key')->values()->all())
        ->and($summary['highlights'] ?? null)->toBe($review->summary['highlights'] ?? [])
        ->and($summary['recommended_next_actions'] ?? null)->toBe($review->summary['recommended_next_actions'] ?? [])
        ->and($summary['delivery_bundle']['contract'] ?? null)->toBe(ReviewPackService::REVIEW_DERIVED_DELIVERY_CONTRACT)
        ->and($summary['delivery_bundle']['executive_entrypoint_file'] ?? null)->toBe(ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME)
        ->and($metadata['delivery_bundle']['contract'] ?? null)->toBe(ReviewPackService::REVIEW_DERIVED_DELIVERY_CONTRACT)
        ->and($metadata['delivery_bundle']['review_pack_id'] ?? null)->toBe((int) $pack->getKey())
        ->and($metadata['delivery_bundle']['released_review']['id'] ?? null)->toBe((int) $review->getKey())
        ->and($metadata['delivery_bundle']['interpretation_version'] ?? null)->toBe($review->controlInterpretationVersion())
        ->and($metadata['delivery_bundle']['entrypoint']['file'] ?? null)->toBe(ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME)
        ->and(collect($metadata['delivery_bundle']['appendix'] ?? [])->pluck('file')->all())->toBe(['metadata.json', 'summary.json', 'sections.json'])
        ->and($filenames)->toContain('metadata.json', 'summary.json', 'sections.json', ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME)
        ->and(collect($filenames)->filter(fn (string $filename): bool => str_starts_with($filename, 'executive-'))->values()->all())->toBe([ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME])
        ->and($executiveEntrypoint)->toContain('# Executive summary')
        ->and($executiveEntrypoint)->toContain('## Executive story')
        ->and($executiveEntrypoint)->toContain('## Structured auditor appendix')
        ->and($executiveEntrypoint)->toContain('metadata.json, summary.json, and sections.json')
        ->and($executiveEntrypoint)->not->toContain((string) $review->fingerprint)
        ->and($executiveEntrypoint)->not->toContain((string) $review->evidenceSnapshot?->fingerprint)
        ->and($executiveEntrypoint)->not->toContain('Reason owner')
        ->and($executiveEntrypoint)->not->toContain('Platform reason family');

    $zip->close();
    unlink($tempFile);

    setTenantPanelContext($tenant);

    Livewire::actingAs($user)
        ->test(TenantReviewPackCard::class, ['record' => $tenant])
        ->assertSee('View review');
});
