<?php

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

/**
 * Immutable audit row per Fintrixor webhook event, attached to an esign_document.
 * Idempotent on (esign_document_id, provider_event_id).
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::create('esign_events', function (Blueprint $t) {
            $t->id();
            $t->foreignId('esign_document_id')->constrained()->cascadeOnDelete();
            $t->foreignId('solicitor_id')->constrained()->cascadeOnDelete();
            $t->string('event_type', 40);                      // EsignEventType value
            $t->string('mapped_status', 24)->nullable();       // EsignStatus value (null = no status implication)
            $t->string('provider_event_id')->nullable();       // X-Esign-Delivery id, or synthesized
            $t->json('payload')->nullable();                   // raw event JSON
            $t->timestamp('occurred_at')->index();
            $t->timestamps();

            $t->index(['esign_document_id', 'event_type']);
            $t->unique(['esign_document_id', 'provider_event_id'], 'esign_events_provider_unique');
        });
    }

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