<?php

declare(strict_types=1);

use App\Models\Finding;
use App\Services\Findings\FindingWorkflowService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('resolves a finding with reason', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $finding = Finding::factory()->for($tenant)->permissionPosture()->create();

    $finding = app(FindingWorkflowService::class)->resolve($finding, $tenant, $user, Finding::RESOLVE_REASON_REMEDIATED);

    expect($finding->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($finding->resolved_at)->not->toBeNull()
        ->and($finding->resolved_reason)->toBe(Finding::RESOLVE_REASON_REMEDIATED);

    $fresh = Finding::query()->find($finding->getKey());
    expect($fresh->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($fresh->resolved_at)->not->toBeNull();
});

it('reopens a resolved finding through the workflow service', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $finding = Finding::factory()->for($tenant)->permissionPosture()->resolved()->create();

    $finding = app(FindingWorkflowService::class)->reopen($finding, $tenant, $user, Finding::REOPEN_REASON_MANUAL_REASSESSMENT);

    expect($finding->status)->toBe(Finding::STATUS_REOPENED)
        ->and($finding->reopened_at)->not->toBeNull()
        ->and($finding->resolved_at)->toBeNull()
        ->and($finding->resolved_reason)->toBeNull();
});

it('supports legacy model helper compatibility for resolve and reopen', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $finding = Finding::factory()->for($tenant)->permissionPosture()->create();

    $finding->resolve(Finding::RESOLVE_REASON_PERMISSION_GRANTED);

    expect($finding->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($finding->resolved_at)->not->toBeNull()
        ->and($finding->resolved_reason)->toBe(Finding::RESOLVE_REASON_PERMISSION_GRANTED);

    $finding->reopen([
        'display_name' => 'Recovered Permission',
        'permission_key' => 'User.Read.All',
    ]);

    expect($finding->status)->toBe(Finding::STATUS_NEW)
        ->and($finding->resolved_at)->toBeNull()
        ->and($finding->resolved_reason)->toBeNull()
        ->and($finding->evidence_jsonb)->toMatchArray([
            'display_name' => 'Recovered Permission',
            'permission_key' => 'User.Read.All',
        ]);
});

it('keeps stale acknowledged metadata as passive data only', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $finding = Finding::factory()->for($tenant)->permissionPosture()->create([
        'status' => 'acknowledged',
        'acknowledged_at' => now(),
        'acknowledged_by_user_id' => $user->getKey(),
    ]);

    expect($finding->status)->toBe('acknowledged')
        ->and($finding->acknowledged_at)->not->toBeNull()
        ->and($finding->acknowledged_by_user_id)->toBe($user->getKey())
        ->and($finding->hasOpenStatus())->toBeFalse();
});

it('exposes v2 open and terminal status helpers', function (): void {
    expect(Finding::openStatuses())->toBe([
        Finding::STATUS_NEW,
        Finding::STATUS_TRIAGED,
        Finding::STATUS_IN_PROGRESS,
        Finding::STATUS_REOPENED,
    ]);

    expect(Finding::terminalStatuses())->toBe([
        Finding::STATUS_RESOLVED,
        Finding::STATUS_CLOSED,
        Finding::STATUS_RISK_ACCEPTED,
    ]);

    expect(Finding::openStatusesForQuery())->toBe(Finding::openStatuses());
});

it('does not treat acknowledged as canonical in v2 helpers', function (): void {
    expect(Finding::canonicalizeStatus('acknowledged'))->toBe('acknowledged');

    expect(Finding::isOpenStatus('acknowledged'))->toBeFalse();
    expect(Finding::isTerminalStatus('acknowledged'))->toBeFalse();
});

it('rejects resolving a stale acknowledged finding', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $finding = Finding::factory()->for($tenant)->permissionPosture()->create([
        'status' => 'acknowledged',
        'acknowledged_at' => now(),
        'acknowledged_by_user_id' => $user->getKey(),
    ]);

    expect(fn () => app(FindingWorkflowService::class)->resolve($finding, $tenant, $user, Finding::RESOLVE_REASON_REMEDIATED))
        ->toThrow(\InvalidArgumentException::class, 'Only open findings can be resolved.');
});

it('has STATUS_RESOLVED constant', function (): void {
    expect(Finding::STATUS_RESOLVED)->toBe('resolved');
});

it('has FINDING_TYPE_PERMISSION_POSTURE constant', function (): void {
    expect(Finding::FINDING_TYPE_PERMISSION_POSTURE)->toBe('permission_posture');
});

it('casts resolved_at as datetime', function (): void {
    $finding = Finding::factory()->permissionPosture()->resolved()->create();
    $fresh = Finding::query()->find($finding->getKey());

    expect($fresh->resolved_at)->toBeInstanceOf(\Illuminate\Support\Carbon::class);
});

it('creates permission posture findings via factory state', function (): void {
    $finding = Finding::factory()->permissionPosture()->create();

    expect($finding->finding_type)->toBe(Finding::FINDING_TYPE_PERMISSION_POSTURE)
        ->and($finding->source)->toBe('permission_check')
        ->and($finding->subject_type)->toBe('permission')
        ->and($finding->severity)->toBe(Finding::SEVERITY_MEDIUM)
        ->and($finding->evidence_jsonb)->toHaveKey('permission_key');
});

it('creates resolved findings via factory state', function (): void {
    $finding = Finding::factory()->resolved()->create();

    expect($finding->status)->toBe(Finding::STATUS_RESOLVED)
        ->and($finding->resolved_at)->not->toBeNull()
        ->and($finding->resolved_reason)->toBe(Finding::RESOLVE_REASON_REMEDIATED);
});
