<?php

namespace Modules\MedRegistry\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Host-global catalog row: one per nwidart module, enriched with the SIFA
 * medical metadata (category, installable_per, spec_key, settings_schema).
 */
class MedregModule extends Model
{
    protected $table = 'medreg_modules';

    protected $guarded = ['id'];

    protected $casts = [
        'dependencies'          => 'array',
        'optional_dependencies' => 'array',
        'conflicts_with'        => 'array',
        'settings_schema'       => 'array',
        'is_present'            => 'boolean',
        'requires_install'      => 'boolean',
        'sort_order'            => 'integer',
    ];

    /** Catalog categories (Specs §6). */
    const CATEGORIES = ['core', 'medical', 'specialty', 'facility', 'support', 'integration'];

    /**
     * Categories treated as "medical" for the default-status fallback: with no
     * instance row at any level these default to DISABLED; everything else
     * (core / support / integration) defaults to ENABLED, so pre-existing
     * non-medical behavior never changes.
     */
    const MEDICAL_CATEGORIES = ['medical', 'specialty', 'facility'];

    /**
     * Spec module ids that resolve to another spec module's host module today
     * (the appointment/encounter engine in ClinicCore covers medical_core,
     * scheduling and outpatient — REUSE-MAP §9).
     *
     * Hospital-preset aliases (P6-T7): MedWard (spec_key inpatient) also
     * delivers bed_management and ICU; ClinicCore delivers the pharmacy
     * dispense workflow. These let the hospital preset resolve to the real
     * host modules instead of reporting them missing.
     */
    const SPEC_ALIASES = [
        'scheduling'     => 'medical_core',
        'outpatient'     => 'medical_core',
        'pharmacy'       => 'medical_core',
        'bed_management' => 'inpatient',
        'icu'            => 'inpatient',
    ];

    const INSTALLABLE_PER = ['tenant', 'facility', 'department'];

    public function instances()
    {
        return $this->hasMany(MedregModuleInstance::class, 'module_id');
    }

    public function isMedical(): bool
    {
        return in_array($this->category, self::MEDICAL_CATEGORIES, true);
    }
}
