<?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('contract_templates', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('business_id')->constrained()->cascadeOnDelete();
            $table->string('name');
            $table->unsignedInteger('version')->default(1);
            $table->string('original_name');
            $table->string('file_path');
            $table->longText('extracted_text')->nullable();
            $table->json('blocks')->nullable();
            $table->json('mappings')->nullable();
            $table->json('required_signatories')->nullable();
            $table->string('status')->default('draft');
            $table->boolean('is_default')->default(false);
            $table->foreignId('uploaded_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->index(['business_id', 'status']);
            $table->index(['business_id', 'is_default']);
        });

        Schema::table('loans', function (Blueprint $table): void {
            $table->foreignId('contract_template_id')->nullable()->after('loan_product_id')->constrained('contract_templates')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('loans', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('contract_template_id');
        });
        Schema::dropIfExists('contract_templates');
    }
};
