<?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) {
            if (! Schema::hasColumn('document_templates', 'meta')) {
                $table->json('meta')->nullable()->after('formatting_options');
            }
            if (! Schema::hasColumn('document_templates', 'action_id')) {
                $table->foreignId('action_id')->nullable()->after('meta')->constrained()->nullOnDelete();
            }
            if (! Schema::hasColumn('document_templates', 'decision_id')) {
                $table->foreignId('decision_id')->nullable()->after('action_id')->constrained()->nullOnDelete();
            }
            if (! Schema::hasColumn('document_templates', 'activity_note_template')) {
                $table->text('activity_note_template')->nullable()->after('decision_id');
            }
            $table->index(['action_id', 'decision_id'], 'document_templates_action_decision_idx');
        });
    }

    public function down(): void
    {
        Schema::table('document_templates', function (Blueprint $table) {
            if (Schema::hasColumn('document_templates', 'activity_note_template')) {
                $table->dropColumn('activity_note_template');
            }
            if (Schema::hasColumn('document_templates', 'decision_id')) {
                $table->dropConstrainedForeignId('decision_id');
            }
            if (Schema::hasColumn('document_templates', 'action_id')) {
                $table->dropConstrainedForeignId('action_id');
            }
            if (Schema::hasColumn('document_templates', 'meta')) {
                $table->dropColumn('meta');
            }
            if (Schema::hasColumn('document_templates', 'action_id') || Schema::hasColumn('document_templates', 'decision_id')) {
                $table->dropIndex('document_templates_action_decision_idx');
            }
        });
    }
};
