<?php

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

/**
 * One row per Fintrixor document (a single template × single recipient).
 * A ContractRequest fans out into one of these per selected contract.
 * provider_document_id (Fintrixor's ULID) is the webhook correlation key.
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::create('esign_documents', function (Blueprint $t) {
            $t->id();
            $t->foreignId('contract_request_id')->constrained()->cascadeOnDelete();
            $t->foreignId('solicitor_id')->constrained()->cascadeOnDelete();
            $t->foreignId('contract_id')->nullable()->constrained()->nullOnDelete();
            $t->string('provider_document_id')->nullable()->unique(); // Fintrixor ULID (correlation key)
            $t->string('status', 24)->default('draft');               // EsignStatus value
            $t->string('recipient_name')->nullable();
            $t->string('recipient_email')->nullable();
            $t->text('signing_url')->nullable();
            $t->string('document_hash')->nullable();
            $t->string('certificate_id')->nullable();
            $t->timestamp('sent_at')->nullable();
            $t->timestamp('viewed_at')->nullable();
            $t->timestamp('signed_at')->nullable();
            $t->timestamp('completed_at')->nullable();
            $t->timestamp('expired_at')->nullable();
            $t->timestamp('failed_at')->nullable();
            $t->json('meta')->nullable();                             // raw create response / misc
            $t->timestamps();

            $t->index(['contract_request_id', 'status']);
        });
    }

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