<?php

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

/**
 * mednotify_templates — the per event × channel message body (spec §7).
 *
 * business_id NULL = a SYSTEM DEFAULT template (seeded by MednotifyTemplatesSeeder).
 * A row with business_id set is a tenant OVERRIDE; the resolver prefers the
 * business override and falls back to the system default. Reset-to-default in
 * the UI simply deletes the override row.
 *
 * body carries {variable} placeholders interpolated at send time. subject is
 * only meaningful for in_app / email.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('mednotify_templates')) {
            Schema::create('mednotify_templates', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id')->nullable(); // NULL = system default
                $t->string('event_key', 100);
                $t->enum('channel', ['in_app', 'email', 'sms', 'whatsapp']);
                $t->string('subject', 191)->nullable();
                $t->text('body');
                $t->boolean('enabled')->default(true);
                $t->timestamps();

                // SHORT index name (MySQL 64-char limit safety).
                $t->unique(['business_id', 'event_key', 'channel'], 'mednotify_tpl_uq');
                $t->index(['business_id', 'event_key'], 'mednotify_tpl_biz_event_idx');
            });
        }
    }

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