<?php

namespace App\Listeners;

use App\Events\ComplaintCreated;
use App\Services\NotificationService;
use App\Jobs\SendNotificationJob;
use App\Models\Notification;

class SendComplaintNotification
{
    /**
     * Create the event listener.
     */
    public function __construct(
        private NotificationService $notificationService
    ) {}

    /**
     * Handle the event.
     */
    public function handle(ComplaintCreated $event): void
    {
        $complaint = $event->complaint;

        // Notify operator
        if ($complaint->operator) {
            $notification = Notification::create([
                'user_id' => $complaint->operator_id,
                'complaint_id' => $complaint->id,
                'type' => 'complaint_created',
                'title' => 'Aduan Baru',
                'message' => "Aduan baru telah diterima: {$complaint->ticket_number}",
                'channel' => 'system',
                'status' => 'pending',
            ]);

            SendNotificationJob::dispatch($notification);
        }

        // Notify Polsek if assigned
        if ($complaint->polsek) {
            foreach ($complaint->polsek->users as $user) {
                $notification = Notification::create([
                    'user_id' => $user->id,
                    'complaint_id' => $complaint->id,
                    'type' => 'complaint_assigned',
                    'title' => 'Aduan Ditugaskan',
                    'message' => "Aduan baru ditugaskan ke {$complaint->polsek->name}",
                    'channel' => 'system',
                    'status' => 'pending',
                ]);

                SendNotificationJob::dispatch($notification);
            }
        }
    }
}
