<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserNotification extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'type',
        'title',
        'body',
        'icon',
        'icon_color',
        'action_url',
        'data',
        'is_read',
        'read_at',
    ];

    protected $casts = [
        'data' => 'array',
        'is_read' => 'boolean',
        'read_at' => 'datetime',
    ];

    // ==================== RELATIONSHIPS ====================

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

    // ==================== SCOPES ====================

    public function scopeUnread($query)
    {
        return $query->where('is_read', false);
    }

    public function scopeByType($query, string $type)
    {
        return $query->where('type', $type);
    }

    public function scopeRecent($query, int $limit = 10)
    {
        return $query->orderBy('created_at', 'desc')->limit($limit);
    }

    // ==================== METHODS ====================

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

    public function getIconClassAttribute()
    {
        return $this->icon ?? $this->getDefaultIcon();
    }

    protected function getDefaultIcon()
    {
        return match($this->type) {
            'subscription' => 'bi-gem',
            'kyc' => 'bi-shield-check',
            'product' => 'bi-box-seam',
            'inquiry' => 'bi-envelope',
            'payment' => 'bi-credit-card',
            'system' => 'bi-megaphone',
            default => 'bi-bell',
        };
    }
}
