<?php

namespace App\Domain\Audit\Listeners;

use App\Domain\Approval\Models\ApprovalRequest;
use App\Domain\Audit\Models\AuditEntry;
use App\Domain\Audit\Services\OcsfMapper;

class LogApprovalDecision
{
    public function handle(object $event): void
    {
        if (! isset($event->approval) || ! $event->approval instanceof ApprovalRequest) {
            return;
        }

        $approval = $event->approval;
        $eventName = 'approval.'.$approval->status->value;
        $ocsf = OcsfMapper::classify($eventName);

        AuditEntry::create([
            'user_id' => $approval->reviewed_by,
            'impersonator_id' => session('impersonating_from'),
            'event' => $eventName,
            'ocsf_class_uid' => $ocsf['class_uid'],
            'ocsf_severity_id' => $ocsf['severity_id'],
            'subject_type' => ApprovalRequest::class,
            'subject_id' => $approval->id,
            'properties' => [
                'experiment_id' => $approval->experiment_id,
                'status' => $approval->status->value,
                'rejection_reason' => $approval->rejection_reason,
            ],
            'created_at' => now(),
        ]);
    }
}
