<?php

namespace Modules\MedNotify\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A notifiable event (spec §7). business_id NULL = system event; a per-business
 * row overrides the label / channels for that tenant.
 */
class MednotifyEvent extends Model
{
    protected $table = 'mednotify_events';

    protected $guarded = ['id'];

    protected $casts = [
        'available_variables' => 'array',
        'default_channels'    => 'array',
        'is_active'           => 'boolean',
    ];

    /**
     * Resolve the effective event for a business + key: a business-specific row
     * takes precedence over the system (business_id NULL) row.
     */
    public static function resolve(int $businessId, string $eventKey): ?self
    {
        return static::where('event_key', $eventKey)
            ->where(function ($q) use ($businessId) {
                $q->where('business_id', $businessId)->orWhereNull('business_id');
            })
            ->orderByRaw('business_id IS NULL') // non-null (business override) first
            ->first();
    }
}
