<?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::table('document_templates', function (Blueprint $table) {
            // Drop original unique index on slug if it exists, then add composite unique (slug, version)
            try {
                $table->dropUnique('document_templates_slug_unique');
            } catch (Throwable $e) {
                // Ignore if already dropped / not present (SQLite memory or prior manual change)
            }
            // Add composite unique to allow multiple versions per slug while preventing duplicate version numbers
            $table->unique(['slug', 'version'], 'document_templates_slug_version_unique');
            // Optional plain index on slug alone (not unique) to speed lookups by slug
            $table->index('slug', 'document_templates_slug_index');
        });
    }

    public function down(): void
    {
        Schema::table('document_templates', function (Blueprint $table) {
            // Drop composite + plain indices
            try {
                $table->dropIndex('document_templates_slug_index');
            } catch (Throwable $e) {
            }
            try {
                $table->dropUnique('document_templates_slug_version_unique');
            } catch (Throwable $e) {
            }
            // Restore original simple unique on slug
            try {
                $table->unique('slug', 'document_templates_slug_unique');
            } catch (Throwable $e) {
            }
        });
    }
};
