<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Features\Agent\Models\Agent;
use App\Features\Auth\Models\User;
use App\Features\Monitoring\Models\AuditLog;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;

class IncidentForensicsTest extends TestCase
{
    use RefreshDatabase;

    public function test_audit_log_detail_includes_forensic_sections(): void
    {
        $admin = User::create([
            'name' => 'Forensics Admin',
            'email' => 'forensics-admin@test.com',
            'password' => bcrypt('password'),
        ]);

        $agent = Agent::create([
            'id' => (string) Str::uuid(),
            'domain' => 'forensics.test',
            'site_name' => 'Forensics Site',
            'status' => 'active',
            'hmac_secret' => str_repeat('a', 32),
            'site_info' => ['plugin_version' => '1.2.2'],
        ]);

        $log = AuditLog::create([
            'agent_id' => $agent->id,
            'severity' => 'warning',
            'event' => 'attack_surface.enumeration_blocked',
            'message' => 'Blocked REST public user enumeration attempt from IP 103.0.0.1',
            'context' => [
                'schema_version' => '1.0',
                'attack_type' => 'REST Public User Enumeration',
                'severity_label' => 'Medium',
                'rule_id' => 'REST_USER_ENUM_BLOCK',
                'rule_name' => 'REST Public User Enumeration Block',
                'trigger_module' => 'attack_surface',
                'action_taken' => 'Blocked',
                'http_method' => 'GET',
                'request_uri' => '/wp-json/wp/v2/users',
                'rest_endpoint' => '/wp/v2/users',
                'response_code' => 401,
                'source_ip' => '103.0.0.1',
                'ip' => '103.0.0.1',
                'user_agent' => 'curl/8.0',
                'request_id' => 'req-test-123',
                'correlation_id' => 'corr-test-456',
                'confidence_score' => 100,
            ],
            'logged_at' => now(),
            'incident_status' => 'open',
        ]);

        $response = $this->actingAs($admin)->getJson("/api/v1/audit-logs/{$log->id}");

        $response->assertStatus(200)
            ->assertJsonPath('log.forensics.overview.event_id', $log->id)
            ->assertJsonPath('log.forensics.attack.attack_type', 'REST Public User Enumeration')
            ->assertJsonPath('log.forensics.request.http_method', 'GET')
            ->assertJsonPath('log.forensics.source.source_ip', '103.0.0.1')
            ->assertJsonPath('log.forensics.detection.rule_id', 'REST_USER_ENUM_BLOCK')
            ->assertJsonPath('log.forensics.action.action_taken', 'Blocked')
            ->assertJsonPath('log.forensics.identifiers.request_id', 'req-test-123')
            ->assertJsonStructure([
                'log' => [
                    'forensics' => [
                        'overview',
                        'attack',
                        'request',
                        'source',
                        'detection',
                        'action',
                        'identifiers',
                    ],
                    'timeline',
                ],
                'related_events',
            ]);
    }

    public function test_enricher_adds_detection_counts_on_ingest(): void
    {
        $agent = Agent::create([
            'id' => (string) Str::uuid(),
            'domain' => 'enrich.test',
            'site_name' => 'Enrich Site',
            'status' => 'active',
            'hmac_secret' => str_repeat('b', 32),
            'site_info' => ['plugin_version' => '1.2.2'],
        ]);

        AuditLog::create([
            'agent_id' => $agent->id,
            'severity' => 'warning',
            'event' => 'attack_surface.enumeration_blocked',
            'message' => 'Prior attempt',
            'context' => ['source_ip' => '198.51.100.10', 'ip' => '198.51.100.10'],
            'logged_at' => now()->subHour(),
        ]);

        $enricher = app(\App\Features\Monitoring\Services\IncidentForensicsEnricher::class);
        $enriched = $enricher->enrich($agent->id, 'attack_surface.enumeration_blocked', [
            'source_ip' => '198.51.100.10',
            'ip' => '198.51.100.10',
            'attack_type' => 'REST Public User Enumeration',
            'rule_id' => 'REST_USER_ENUM_BLOCK',
            'action_taken' => 'Blocked',
        ]);

        $this->assertSame(1, $enriched['previous_detections_ip']);
        $this->assertSame(1, $enriched['previous_detections_website']);
        $this->assertSame($agent->id, $enriched['website_id']);
        $this->assertSame('1.2.2', $enriched['plugin_version']);
    }
}
