<?php

declare(strict_types=1);

use App\Filament\Resources\AlertRuleResource;
use App\Models\AlertDelivery;
use App\Models\AlertDestination;
use App\Models\AlertRule;
use App\Models\Finding;
use App\Services\Alerts\AlertDispatchService;
use App\Support\Workspaces\WorkspaceContext;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function createEntraAlertRuleWithDestination(int $workspaceId, string $minSeverity, int $cooldownSeconds = 0): array
{
    $destination = AlertDestination::factory()->create([
        'workspace_id' => $workspaceId,
        'is_enabled' => true,
    ]);

    $rule = AlertRule::factory()->create([
        'workspace_id' => $workspaceId,
        'event_type' => AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH,
        'minimum_severity' => $minSeverity,
        'is_enabled' => true,
        'cooldown_seconds' => $cooldownSeconds,
    ]);

    $rule->destinations()->attach($destination->getKey(), [
        'workspace_id' => $workspaceId,
    ]);

    return [$rule, $destination];
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

it('queues delivery when entra admin role finding matches alert rule severity', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);

    [$rule, $destination] = createEntraAlertRuleWithDestination($workspaceId, 'high');

    $finding = Finding::factory()->entraAdminRoles()->create([
        'workspace_id' => $workspaceId,
        'managed_environment_id' => $tenant->getKey(),
        'severity' => Finding::SEVERITY_CRITICAL,
        'status' => Finding::STATUS_NEW,
    ]);

    $event = [
        'event_type' => AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH,
        'managed_environment_id' => (int) $tenant->getKey(),
        'severity' => Finding::SEVERITY_CRITICAL,
        'fingerprint_key' => 'finding:'.(int) $finding->getKey(),
        'title' => 'High-privilege Entra admin role detected',
        'body' => 'Role "Global Administrator" assigned to Alice Admin (severity: critical).',
        'metadata' => ['finding_id' => (int) $finding->getKey()],
    ];

    $dispatchService = app(AlertDispatchService::class);
    $workspace = \App\Models\Workspace::query()->find($workspaceId);

    $created = $dispatchService->dispatchEvent($workspace, $event);

    expect($created)->toBe(1);

    $delivery = AlertDelivery::query()
        ->where('workspace_id', $workspaceId)
        ->where('event_type', AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH)
        ->first();

    expect($delivery)->not->toBeNull()
        ->and($delivery->status)->toBe(AlertDelivery::STATUS_QUEUED)
        ->and($delivery->severity)->toBe(Finding::SEVERITY_CRITICAL);
});

it('does not queue delivery when finding severity is below minimum', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);

    [$rule, $destination] = createEntraAlertRuleWithDestination($workspaceId, 'critical');

    $event = [
        'event_type' => AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH,
        'managed_environment_id' => (int) $tenant->getKey(),
        'severity' => Finding::SEVERITY_HIGH,
        'fingerprint_key' => 'finding:999',
        'title' => 'High-privilege Entra admin role detected',
        'body' => 'Role "Privileged Role Administrator" assigned to Bob (severity: high).',
        'metadata' => [],
    ];

    $dispatchService = app(AlertDispatchService::class);
    $workspace = \App\Models\Workspace::query()->find($workspaceId);

    $created = $dispatchService->dispatchEvent($workspace, $event);

    expect($created)->toBe(0);
});

it('suppresses duplicate delivery via fingerprint cooldown', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);

    [$rule, $destination] = createEntraAlertRuleWithDestination($workspaceId, 'high', cooldownSeconds: 3600);

    $finding = Finding::factory()->entraAdminRoles()->create([
        'workspace_id' => $workspaceId,
        'managed_environment_id' => $tenant->getKey(),
        'severity' => Finding::SEVERITY_CRITICAL,
        'status' => Finding::STATUS_NEW,
    ]);

    $event = [
        'event_type' => AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH,
        'managed_environment_id' => (int) $tenant->getKey(),
        'severity' => Finding::SEVERITY_CRITICAL,
        'fingerprint_key' => 'finding:'.(int) $finding->getKey(),
        'title' => 'High-privilege Entra admin role detected',
        'body' => 'Role "Global Administrator" assigned to Alice Admin.',
        'metadata' => ['finding_id' => (int) $finding->getKey()],
    ];

    $dispatchService = app(AlertDispatchService::class);
    $workspace = \App\Models\Workspace::query()->find($workspaceId);

    // First dispatch — should create a QUEUED delivery
    $firstCreated = $dispatchService->dispatchEvent($workspace, $event);
    expect($firstCreated)->toBe(1);

    // Second dispatch — same fingerprint within cooldown → SUPPRESSED
    $secondCreated = $dispatchService->dispatchEvent($workspace, $event);
    expect($secondCreated)->toBe(1);

    $deliveries = AlertDelivery::query()
        ->where('workspace_id', $workspaceId)
        ->where('event_type', AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH)
        ->orderBy('id')
        ->get();

    expect($deliveries)->toHaveCount(2)
        ->and($deliveries[0]->status)->toBe(AlertDelivery::STATUS_QUEUED)
        ->and($deliveries[1]->status)->toBe(AlertDelivery::STATUS_SUPPRESSED);
});

it('resolved findings are excluded from entraAdminRolesHighEvents', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);

    // Create a resolved finding — should not appear in events
    Finding::factory()->entraAdminRoles()->resolved()->create([
        'workspace_id' => $workspaceId,
        'managed_environment_id' => $tenant->getKey(),
        'severity' => Finding::SEVERITY_CRITICAL,
    ]);

    $job = new \App\Jobs\Alerts\EvaluateAlertsJob($workspaceId);
    $reflection = new ReflectionMethod($job, 'entraAdminRolesHighEvents');

    $events = $reflection->invoke(
        $job,
        $workspaceId,
        CarbonImmutable::now('UTC')->subHours(1),
    );

    expect($events)->toBe([]);
});

it('reopened findings are included in entraAdminRolesHighEvents', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);

    $finding = Finding::factory()->entraAdminRoles()->create([
        'workspace_id' => $workspaceId,
        'managed_environment_id' => $tenant->getKey(),
        'severity' => Finding::SEVERITY_CRITICAL,
        'status' => Finding::STATUS_REOPENED,
        'reopened_at' => now(),
    ]);

    $job = new \App\Jobs\Alerts\EvaluateAlertsJob($workspaceId);
    $reflection = new ReflectionMethod($job, 'entraAdminRolesHighEvents');

    $events = $reflection->invoke(
        $job,
        $workspaceId,
        CarbonImmutable::now('UTC')->subHours(1),
    );

    expect($events)->toHaveCount(1)
        ->and($events[0]['event_type'])->toBe(AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH)
        ->and($events[0]['managed_environment_id'])->toBe((int) $tenant->getKey())
        ->and($events[0]['metadata']['finding_id'])->toBe((int) $finding->getKey());
});

it('new event type appears in AlertRuleResource event type options', function (): void {
    $options = AlertRuleResource::eventTypeOptions();

    expect($options)->toHaveKey(AlertRule::EVENT_SLA_DUE)
        ->and($options[AlertRule::EVENT_SLA_DUE])->toBe('SLA due')
        ->and($options)->toHaveKey(AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH)
        ->and($options[AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH])->toBe('Entra admin roles (high privilege)');
});
