<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * medreg_modules — HOST-GLOBAL module catalog (deliberately business_id-less;
 * one row per nwidart module on this host). Seeded/refreshed by
 * MedregCatalogSeeder / `medreg:sync-catalog` from module.json manifests
 * (extra.medical block) with a curated retro-fit map for pre-existing modules
 * (REUSE-MAP §6: wrap, never replace, the nwidart manifests).
 *
 * All MedRegistry tables are prefixed medreg_. References into ERP core tables
 * are plain indexed columns — no cross-table FK constraints — matching the
 * existing module convention (see Modules\Vrc migrations).
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('medreg_modules')) {
            Schema::create('medreg_modules', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->string('module_key', 100)->unique();   // nwidart StudlyCase name, e.g. DentalClinic
                $t->string('alias', 100);                  // nwidart lowercase alias
                $t->string('display_name', 191);
                $t->text('description')->nullable();
                $t->string('icon', 100)->nullable();
                $t->enum('category', ['core', 'medical', 'specialty', 'facility', 'support', 'integration'])
                    ->default('core');
                // Spec module id ('medical_core', 'dental', 'laboratory', …) —
                // maps SIFA spec names to real host modules. Not unique: several
                // modules may serve one spec module (LabCore + ClinicLab → laboratory).
                $t->string('spec_key', 100)->nullable()->index();
                $t->json('dependencies')->nullable();          // spec_keys this module needs
                $t->json('optional_dependencies')->nullable(); // spec_keys that enhance it
                $t->json('conflicts_with')->nullable();        // spec_keys / module_keys
                $t->enum('installable_per', ['tenant', 'facility', 'department'])->default('tenant');
                $t->json('settings_schema')->nullable();       // P1-T5 generic settings UI schema
                $t->string('version', 30)->nullable();
                $t->boolean('is_present')->default(false);     // module folder exists on this host
                $t->integer('sort_order')->default(0);
                $t->timestamps();
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('medreg_modules');
    }
};
