<?php

namespace Modules\MedNotify\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Per event × channel message template. business_id NULL = system default;
 * a business row overrides it. Reset-to-default deletes the override row.
 */
class MednotifyTemplate extends Model
{
    protected $table = 'mednotify_templates';

    protected $guarded = ['id'];

    protected $casts = [
        'enabled' => 'boolean',
    ];

    /**
     * The effective template for a business + event + channel: the tenant
     * override if present, else the system default. Returns null when neither
     * exists (event has no template for that channel).
     */
    public static function resolve(int $businessId, string $eventKey, string $channel): ?self
    {
        return static::where('event_key', $eventKey)
            ->where('channel', $channel)
            ->where(function ($q) use ($businessId) {
                $q->where('business_id', $businessId)->orWhereNull('business_id');
            })
            ->orderByRaw('business_id IS NULL') // business override first
            ->first();
    }

    /** The shipped system default (business_id NULL) for reset-to-default. */
    public static function systemDefault(string $eventKey, string $channel): ?self
    {
        return static::whereNull('business_id')
            ->where('event_key', $eventKey)
            ->where('channel', $channel)
            ->first();
    }
}
