<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class NexusNotification extends Model
{
    protected $fillable = ['user_id','type','title','body','url','icon','color','read_at'];

    protected function casts(): array {
        return ['read_at' => 'datetime'];
    }

    public function user(): BelongsTo { return $this->belongsTo(User::class); }

    public function scopeUnread($q) { return $q->whereNull('read_at'); }
    public function scopeForUser($q, int $userId) { return $q->where('user_id', $userId); }

    public function markAsRead(): void {
        if (!$this->read_at) {
            $this->update(['read_at' => now()]);
        }
    }

    // Fábrica de notificaciones tipadas
    public static function send(int $userId, string $type, string $title, string $body, ?string $url = null): self
    {
        $meta = match($type) {
            'ticket_created'        => ['icon' => 'plus-circle',   'color' => 'blue'],
            'ticket_assigned'       => ['icon' => 'user-check',    'color' => 'purple'],
            'ticket_updated'        => ['icon' => 'pencil',        'color' => 'gray'],
            'ticket_comment'        => ['icon' => 'chat',          'color' => 'blue'],
            'ticket_status_changed' => ['icon' => 'arrows',        'color' => 'indigo'],
            'ticket_closed'         => ['icon' => 'check-circle',  'color' => 'green'],
            'sla_warning'           => ['icon' => 'clock',         'color' => 'yellow'],
            'sla_breached'          => ['icon' => 'exclamation',   'color' => 'red'],
            default                 => ['icon' => 'bell',          'color' => 'gray'],
        };

        return static::create([
            'user_id' => $userId,
            'type'    => $type,
            'title'   => $title,
            'body'    => $body,
            'url'     => $url,
            'icon'    => $meta['icon'],
            'color'   => $meta['color'],
        ]);
    }
}
