<?php

declare(strict_types=1);

use App\Models\StoredReport;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('persists fingerprint and previous_fingerprint columns', function (): void {
    [$user, $tenant] = createUserWithTenant();

    $report = StoredReport::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_ENTRA_ADMIN_ROLES,
        'fingerprint' => str_repeat('a', 64),
        'previous_fingerprint' => str_repeat('b', 64),
    ]);

    $fresh = StoredReport::query()->find($report->getKey());

    expect($fresh->fingerprint)->toBe(str_repeat('a', 64))
        ->and($fresh->previous_fingerprint)->toBe(str_repeat('b', 64));
});

it('prevents duplicate (managed_environment_id, report_type, fingerprint) via unique index', function (): void {
    [$user, $tenant] = createUserWithTenant();
    $fingerprint = hash('sha256', 'test-content');

    StoredReport::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_ENTRA_ADMIN_ROLES,
        'fingerprint' => $fingerprint,
    ]);

    expect(fn () => StoredReport::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_ENTRA_ADMIN_ROLES,
        'fingerprint' => $fingerprint,
    ]))->toThrow(\Illuminate\Database\QueryException::class);
});

it('allows null fingerprint for existing reports without fingerprinting', function (): void {
    [$user, $tenant] = createUserWithTenant();

    $report = StoredReport::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'report_type' => StoredReport::REPORT_TYPE_PERMISSION_POSTURE,
        'fingerprint' => null,
        'previous_fingerprint' => null,
    ]);

    $fresh = StoredReport::query()->find($report->getKey());

    expect($fresh->fingerprint)->toBeNull()
        ->and($fresh->previous_fingerprint)->toBeNull();
});
