<?php

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

/**
 * mednotify_preferences — per-user, per-event, per-channel opt-out + delivery
 * mode (spec §7). Users manage their own rows via the "My preferences" matrix.
 *
 *   event_key NULL = applies to ALL events
 *   channel   NULL = applies to ALL channels
 * The most specific matching row wins at send time (see PreferenceResolver).
 * quiet_from/quiet_to define a daily quiet window; anything sent inside it is
 * routed to the digest queue instead of delivered immediately.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('mednotify_preferences')) {
            Schema::create('mednotify_preferences', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedInteger('user_id');
                $t->string('event_key', 100)->nullable(); // NULL = all events
                $t->enum('channel', ['in_app', 'email', 'sms', 'whatsapp'])->nullable(); // NULL = all channels
                $t->boolean('enabled')->default(true);
                $t->enum('digest', ['immediate', 'hourly', 'daily'])->default('immediate');
                $t->time('quiet_from')->nullable();
                $t->time('quiet_to')->nullable();
                $t->timestamps();

                $t->unique(['business_id', 'user_id', 'event_key', 'channel'], 'mednotify_pref_uq');
                $t->index(['business_id', 'user_id'], 'mednotify_pref_biz_user_idx');
            });
        }
    }

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