<?php

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

/**
 * mednotify_events — the registry of notifiable events (spec §7).
 *
 * business_id NULL = a SYSTEM event (shipped by MedNotify or registered by
 * another module). A per-business row (business_id set) lets a tenant add or
 * override an event's label / channels. Modules register their events here so
 * they surface in the template + preference UI.
 *
 * All MedNotify tables are prefixed mednotify_. References into ERP core tables
 * (business, users, contacts) are plain indexed columns — no cross-table FK
 * constraints — matching the existing module convention (see Modules\Vrc).
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('mednotify_events')) {
            Schema::create('mednotify_events', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id')->nullable(); // NULL = system event
                $t->string('event_key', 100);                   // e.g. appointment.created
                $t->string('module_key', 100)->nullable();      // owning module (Vrc, ClinicCore, MedNotify…)
                $t->string('label', 191);
                $t->text('description')->nullable();
                $t->json('available_variables')->nullable();     // [{name, label}] shown as hints in the UI
                $t->json('default_channels')->nullable();        // ['in_app','email',…] default fan-out
                $t->boolean('is_active')->default(true);
                $t->timestamps();

                $t->unique(['business_id', 'event_key'], 'mednotify_events_biz_key_uq');
                $t->index(['business_id', 'is_active'], 'mednotify_events_biz_active_idx');
                $t->index('module_key', 'mednotify_events_module_idx');
            });
        }
    }

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