<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('formula_results', function (Blueprint $table) {
            // ✅ اضافه کردن ستون attempt_id اگر وجود ندارد
            if (!Schema::hasColumn('formula_results', 'attempt_id')) {
                $table->foreignId('attempt_id')->nullable()->constrained('test_attempts')->cascadeOnDelete();
            }

            // ✅ اضافه کردن سایر ستون‌های احتمالی缺失
            if (!Schema::hasColumn('formula_results', 'formula_code')) {
                $table->string('formula_code')->nullable()->after('formula_id');
            }

            if (!Schema::hasColumn('formula_results', 'input_values')) {
                $table->json('input_values')->nullable()->after('formula_code');
            }

            if (!Schema::hasColumn('formula_results', 'expression_snapshot')) {
                $table->text('expression_snapshot')->nullable()->after('input_values');
            }

            if (!Schema::hasColumn('formula_results', 'result_type')) {
                $table->string('result_type')->nullable()->after('expression_snapshot');
            }

            if (!Schema::hasColumn('formula_results', 'result_value')) {
                $table->text('result_value')->nullable()->after('result_type');
            }

            if (!Schema::hasColumn('formula_results', 'execution_time')) {
                $table->decimal('execution_time', 10, 6)->nullable()->after('result_value');
            }
        });
    }

    public function down()
    {
        Schema::table('formula_results', function (Blueprint $table) {
            $table->dropForeign(['attempt_id']);
            $table->dropColumn([
                'attempt_id',
                'formula_code',
                'input_values',
                'expression_snapshot',
                'result_type',
                'result_value',
                'execution_time',
            ]);
        });
    }
};
