<?php

namespace App\Listeners;

use App\Events\IncidentOpened;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;

class NotifyAssigneeOfIncident implements ShouldQueue
{
    public string $queue = 'notifications';

    public function handle(IncidentOpened $event): void
    {
        $incident = $event->incident;
        $title = "[{$incident->severity}] {$incident->title}";

        $recipients = User::query()
            ->where('status', 'active')
            ->where(function ($q) use ($incident) {
                $q->whereIn('role', ['super_admin', 'admin', 'server_admin']);
                if ($incident->assigned_to) {
                    $q->orWhere('id', $incident->assigned_to);
                }
            })
            ->get();

        foreach ($recipients as $user) {
            Notification::create([
                'user_id' => $user->id,
                'type' => 'incident',
                'severity' => $incident->severity,
                'title' => $title,
                'message' => $incident->description,
                'source' => 'auto',
                'subject_type' => $incident->subject_type,
                'subject_id' => $incident->subject_id,
            ]);
        }
    }
}
