<?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;
use App\Domain\Shared\Traits\BelongsToBranch;

class NotificationLog extends Model
{
    use BelongsToAcademy, BelongsToBranch;

    /**
     * branch_id NULL means every branch uses this row — catalogue and
     * configuration, not an operational record owned by one branch.
     */
    protected static bool $branchScopeAllowsShared = true;
    /**
     * Immutable — no updated_at.
     */
    const UPDATED_AT = null;

    protected $table = 'notification_logs';

    protected $fillable = [
        'academy_id', 'branch_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));
    }
}
