<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('witness_statement_versions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('solicitor_id')->constrained('solicitors')->cascadeOnDelete();
            $table->foreignId('witness_statement_id')->constrained('witness_statements')->cascadeOnDelete();
            $table->unsignedInteger('version_number');
            // The generated PDF stored as a Document (optional — snapshot survives even if the doc is removed).
            $table->foreignId('document_id')->nullable()->constrained('documents')->nullOnDelete();
            // Immutable copies taken at generation time. These must NOT be FKs to live
            // answer/exhibit rows — a version must never change when data changes later.
            $table->json('answers_snapshot');
            $table->json('exhibits_snapshot');
            $table->json('options')->nullable();
            $table->foreignId('generated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('generated_at');
            $table->timestamps();

            $table->unique(['witness_statement_id', 'version_number'], 'wsv_unique_version');
        });
    }

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