<?php

namespace App\Domain\Notification\Models;

use App\Domain\Notification\Enums\NotificationChannel;
use App\Domain\Notification\Enums\NotificationStatus;
use App\Domain\Shared\Traits\BelongsToAcademy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class NotificationLog extends Model
{
    use BelongsToAcademy;
    /**
     * Immutable — no updated_at.
     */
    const UPDATED_AT = null;

    protected $table = 'notification_logs';

    protected $fillable = [
        'academy_id',
        'recipient_type',
        'recipient_id',
        'event_type',
        'channel',
        'subject',
        'body',
        'status',
        'error_message',
        'sent_at',
        'read_at',
        'metadata',
    ];

    protected $casts = [
        'channel' => NotificationChannel::class,
        'status' => NotificationStatus::class,
        'sent_at' => 'datetime',
        'read_at' => 'datetime',
        'metadata' => 'array',
    ];

    // Scopes

    public function scopeUnread(Builder $query): Builder
    {
        return $query->where('status', NotificationStatus::Sent)
                     ->where('channel', NotificationChannel::InApp);
    }

    public function scopeForRecipient(Builder $query, string $type, int $id): Builder
    {
        return $query->where('recipient_type', $type)
                     ->where('recipient_id', $id);
    }

    public function scopeForEvent(Builder $query, string $eventType): Builder
    {
        return $query->where('event_type', $eventType);
    }

    public function scopeRecent(Builder $query, int $days = 30): Builder
    {
        return $query->where('created_at', '>=', now()->subDays($days));
    }
}
