<?php

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

/**
 * medreg_module_instances — the per-tenant / per-facility / per-department
 * module instance layer (P1-T2, Specs §6 module_instance). This layer sits ON
 * TOP of the existing gates and never replaces them:
 *   - host install stays `system.{module}_version` (ModuleUtil::isModuleInstalled)
 *   - tenant entitlement stays the Superadmin subscription
 *     (ModuleUtil::hasThePermissionInSubscription)
 * business_location_id / department_id NULL = tenant-level instance.
 *
 * Per D4 (TENANCY-PERMISSIONS-AUDIT): uninstall deletes the instance row only —
 * module data is always kept.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('medreg_module_instances')) {
            Schema::create('medreg_module_instances', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id')->index();
                $t->unsignedBigInteger('module_id'); // FK medreg_modules (own table, FK allowed)
                $t->unsignedInteger('business_location_id')->nullable(); // ERP business_locations.id (plain column)
                $t->unsignedInteger('department_id')->nullable();        // clc_departments.id (plain column)
                $t->enum('status', ['installed', 'enabled', 'disabled', 'soft_locked'])->default('enabled');
                $t->json('settings')->nullable();       // P1-T5 per-instance settings (validated by settings_schema)
                $t->timestamp('installed_at')->nullable();
                $t->timestamps();

                // Short custom index name — the auto-generated name would blow
                // MySQL's 64-char identifier limit.
                $t->unique(['module_id', 'business_id', 'business_location_id', 'department_id'], 'medreg_instance_unique');

                $t->foreign('module_id', 'medreg_instance_module_fk')
                    ->references('id')->on('medreg_modules')->onDelete('cascade');
            });
        }
    }

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