<?php

declare(strict_types=1);

use App\Jobs\GenerateReviewPackJob;
use App\Models\StoredReport;
use App\Services\ReviewPackService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;

uses(RefreshDatabase::class);

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

it('redacts protected report fields while preserving safe configuration evidence in review-pack exports', function (): void {
    [$user, $tenant] = createUserWithTenant();

    StoredReport::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_PERMISSION_POSTURE,
        'payload' => [
            'passwordMinimumLength' => 14,
            'clientSecret' => 'super-secret-value',
        ],
    ]);

    Notification::fake();

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

    $job = new GenerateReviewPackJob(
        reviewPackId: (int) $pack->getKey(),
        operationRunId: (int) $pack->operation_run_id,
    );

    app()->call([$job, 'handle']);

    $pack->refresh();

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

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

    $report = json_decode((string) $zip->getFromName('reports/permission_posture.json'), true, 512, JSON_THROW_ON_ERROR);
    $metadata = json_decode((string) $zip->getFromName('metadata.json'), true, 512, JSON_THROW_ON_ERROR);

    expect($report['passwordMinimumLength'] ?? null)->toBe(14);
    expect($report['clientSecret'] ?? null)->toBe('[REDACTED]');
    expect(data_get($metadata, 'redaction_integrity.protected_values_hidden'))->toBeTrue();

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