<?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('document_templates', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('custom_name')->nullable();
            $table->text('description')->nullable();
            $table->string('core_entity'); // e.g. 'contract'
            $table->json('entities'); // list of related entities allowed
            $table->json('columns'); // map entity => allowed columns
            $table->unsignedInteger('version')->default(1);
            $table->string('engine')->default('tokens');
            $table->string('file_path');
            $table->string('file_hash', 64);
            $table->unsignedBigInteger('file_size');
            $table->string('mime_type', 120);
            $table->boolean('active')->default(true);
            $table->foreignId('created_by')->constrained('users');
            $table->foreignId('updated_by')->nullable()->constrained('users');
            $table->timestamps();
            $table->index(['core_entity', 'active']);
        });

        Schema::table('documents', function (Blueprint $table) {
            if (! Schema::hasColumn('documents', 'template_id')) {
                $table->foreignId('template_id')->nullable()->after('uuid')->constrained('document_templates');
            }
            if (! Schema::hasColumn('documents', 'template_version')) {
                $table->unsignedInteger('template_version')->nullable()->after('template_id');
            }
        });
    }

    public function down(): void
    {
        Schema::table('documents', function (Blueprint $table) {
            if (Schema::hasColumn('documents', 'template_version')) {
                $table->dropColumn('template_version');
            }
            if (Schema::hasColumn('documents', 'template_id')) {
                $table->dropConstrainedForeignId('template_id');
            }
        });
        Schema::dropIfExists('document_templates');
    }
};
