<?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
    {
        if (Schema::hasColumn('exams', 'result_template_id')) {
            Schema::table('exams', function (Blueprint $table) {
                $table->dropForeign(['result_template_id']);
                $table->dropColumn('result_template_id');
            });
        }

        Schema::dropIfExists('result_templates');
    }

    public function down(): void
    {
        // Recreate minimal result_templates table and column in exams for rollback
        if (!Schema::hasTable('result_templates')) {
            Schema::create('result_templates', function (Blueprint $table) {
                $table->id();
                $table->string('name')->nullable();
                $table->timestamps();
            });
        }

        if (!Schema::hasColumn('exams', 'result_template_id')) {
            Schema::table('exams', function (Blueprint $table) {
                $table->foreignId('result_template_id')->nullable()->after('exam_type_id')->constrained('result_templates')->onDelete('set null');
            });
        }
    }
};


