<?php

namespace App\Notifications;

use App\Events\NotificationSent;
use App\Models\Notification as NotificationModel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class SystemManagementNotification extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct(
        protected string $title,
        protected string $message,
        protected string $type = 'info',
        protected string $recipient = 'Developer',
        protected ?int $createdBy = null
    ) {
        $this->createdBy = $createdBy ?? Auth::id();
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        // Manually save to our custom notifications table here
        $this->saveToCustomDatabase($notifiable);

        return [];
    }

    /**
     * Save to the custom notifications table.
     */
    protected function saveToCustomDatabase(object $notifiable): void
    {
        // Prevent duplicate entries for the same system notification within a short window.
        // This is necessary because system notifications are often sent to multiple users
        // (e.g., all Administrators), but we only want one entry in the global log.
        $recent = NotificationModel::where('title', $this->title)
            ->where('message', $this->message)
            ->where('recipient', $this->recipient)
            ->where('created_at', '>=', now()->subSeconds(5))
            ->exists();

        if ($recent) {
            return;
        }

        $notification = NotificationModel::create([
            'title' => $this->title,
            'message' => $this->message,
            'type' => $this->type,
            'recipient' => $this->recipient,
            'created_by' => $this->createdBy,
        ]);

        // Broadcast a NotificationSent event so the UI updates in real-time.
        // We do this here once after the database record is created.
        event(new NotificationSent($notification));
    }
}
