<?php

declare(strict_types=1);

use App\Filament\Resources\ReviewPackResource;
use App\Jobs\GenerateReviewPackJob;
use App\Services\ReviewPackService;
use App\Support\ReviewPackStatus;
use Illuminate\Support\Facades\Storage;

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

it('generates a review-derived executive pack with tenant-review metadata and filtered sections', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $review = composeTenantReviewForTest($tenant, $user);

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

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

    $pack->refresh();
    $review->refresh()->load('evidenceSnapshot');

    expect($pack->tenant_review_id)->toBe((int) $review->getKey())
        ->and($pack->status)->toBe(ReviewPackStatus::Ready->value)
        ->and($pack->summary['tenant_review_id'] ?? null)->toBe((int) $review->getKey())
        ->and($pack->summary['review_status'] ?? null)->toBe((string) $review->status)
        ->and($review->current_export_review_pack_id)->toBe((int) $pack->getKey())
        ->and(data_get($review->summary, 'has_ready_export'))->toBeTrue();

    $zipContent = Storage::disk('exports')->get((string) $pack->file_path);
    $tempFile = tempnam(sys_get_temp_dir(), 'review-derived-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);

    expect(data_get($metadata, 'tenant_name'))->toBe('[REDACTED]')
        ->and(data_get($metadata, 'delivery_bundle.entrypoint.file'))->toBe(ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME)
        ->and(data_get($metadata, 'delivery_bundle.entrypoint.role'))->toBe('executive_entrypoint')
        ->and(data_get($metadata, 'delivery_bundle.appendix.0.file'))->toBe('metadata.json')
        ->and(data_get($metadata, 'delivery_bundle.appendix.1.file'))->toBe('summary.json')
        ->and(data_get($metadata, 'delivery_bundle.appendix.2.file'))->toBe('sections.json')
        ->and(data_get($metadata, 'options.include_operations'))->toBeFalse()
        ->and(data_get($summary, 'delivery_bundle.executive_entrypoint_file'))->toBe(ReviewPackService::EXECUTIVE_ENTRYPOINT_FILENAME)
        ->and(data_get($summary, 'tenant_review_id'))->toBe((int) $review->getKey())
        ->and(collect($sections)->pluck('section_key')->all())->not->toContain('operations_health')
        ->and($executiveEntrypoint)->toContain('Tenant: [REDACTED]')
        ->and($executiveEntrypoint)->toContain('This executive entrypoint is the first file to read')
        ->and($executiveEntrypoint)->not->toContain((string) $review->fingerprint)
        ->and($executiveEntrypoint)->not->toContain((string) $review->evidenceSnapshot?->fingerprint);

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

    $this->actingAs($user)
        ->get(ReviewPackResource::getUrl('view', ['record' => $pack], tenant: $tenant, panel: 'tenant'))
        ->assertOk()
        ->assertSee('Outcome summary')
        ->assertDontSee('Artifact truth')
        ->assertSee('#'.$review->getKey())
        ->assertSee('Review status');
});
