<?php

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

/**
 * mednotify_log — one row per (event, channel, recipient) delivery attempt.
 * The audit trail behind the "Log" screen. Adapters ALWAYS write here (never
 * throw), so a failed send lands as status=failed with the error captured.
 *
 *   recipient_type = user | contact  (an ERP users.id or contacts.id)
 *   status = queued | sent | failed | digested | skipped
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('mednotify_log')) {
            Schema::create('mednotify_log', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->string('event_key', 100);
                $t->enum('channel', ['in_app', 'email', 'sms', 'whatsapp']);
                $t->enum('recipient_type', ['user', 'contact']);
                $t->unsignedBigInteger('recipient_id');
                $t->string('rendered_subject', 191)->nullable();
                $t->enum('status', ['queued', 'sent', 'failed', 'digested', 'skipped'])->default('queued');
                $t->text('error')->nullable();
                $t->timestamp('sent_at')->nullable();
                $t->timestamps();

                $t->index(['business_id', 'event_key'], 'mednotify_log_biz_event_idx');
                $t->index(['business_id', 'status'], 'mednotify_log_biz_status_idx');
                $t->index(['business_id', 'created_at'], 'mednotify_log_biz_created_idx');
            });
        }
    }

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