<?php

namespace App\Models;

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

class DwNotification extends Model
{
    protected $table = 'dw_notifications';

    protected $fillable = [
        'client_id',
        'user_id',
        'fingerprint',
        'category',
        'source_type',
        'source_id',
        'level',
        'title',
        'message',
        'action_label',
        'action_url',
        'payload',
        'read_at',
        'dismissed_at',
        'expires_at',
    ];

    protected $casts = [
        'payload' => 'array',
        'read_at' => 'datetime',
        'dismissed_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

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

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

    public function scopeUnread(Builder $query): Builder
    {
        return $query->whereNull('read_at')->whereNull('dismissed_at');
    }

    public function scopeVisible(Builder $query): Builder
    {
        return $query->whereNull('dismissed_at')
            ->where(function (Builder $q) {
                $q->whereNull('expires_at')->orWhere('expires_at', '>=', now());
            });
    }

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

    public function dismiss(): void
    {
        $this->forceFill(['dismissed_at' => now(), 'read_at' => $this->read_at ?: now()])->save();
    }

    public function badgeClass(): string
    {
        return match ($this->level) {
            'danger', 'critical', 'error' => 'badge-danger',
            'warning' => 'badge-warning',
            'success' => 'badge-success',
            default => 'badge-info',
        };
    }

    public function label(): string
    {
        return match ($this->level) {
            'danger', 'critical', 'error' => 'Kritik',
            'warning' => 'Uyarı',
            'success' => 'Başarılı',
            default => 'Bilgi',
        };
    }
}
