<?php

namespace App\Domain\Notification\Models;

use App\Domain\Notification\Enums\NotificationChannel;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class NotificationTemplate extends Model
{
    use HasUuid, Auditable;

    protected $table = 'notification_templates';

    protected $fillable = [
        'academy_id',
        'event_type',
        'channel',
        'subject',
        'body',
        'variables',
        'is_active',
        'locale',
        'metadata',
    ];

    protected $casts = [
        'channel' => NotificationChannel::class,
        'is_active' => 'boolean',
        'variables' => 'array',
        'metadata' => 'array',
    ];

    // Relationships

    public function academy(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Shared\Models\Academy::class);
    }

    // Scopes

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

    public function scopeForChannel(Builder $query, NotificationChannel $channel): Builder
    {
        return $query->where('channel', $channel);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    /**
     * Resolve template: academy-specific first, then platform default.
     */
    public function scopeForAcademy(Builder $query, ?int $academyId): Builder
    {
        return $query->where(function (Builder $q) use ($academyId) {
            $q->where('academy_id', $academyId)
              ->orWhereNull('academy_id');
        })->orderByRaw('academy_id IS NULL ASC');
    }
}
