<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('questions', function (Blueprint $table) {
            $table->dropForeign(['exam_id']);
            $table->dropColumn('exam_id');
            
            $table->foreignId('lesson_id')->nullable()->constrained('lessons')->nullOnDelete();
            $table->foreignId('classroom_id')->nullable()->constrained('classrooms')->nullOnDelete();
            $table->enum('type', ['pg', 'pg_kompleks', 'menjodohkan', 'isian', 'uraian'])->default('pg');
            $table->enum('difficulty', ['mudah', 'sedang', 'sulit'])->default('sedang');
            
            // Drop old answer field and recreate to avoid casting issues without DBAL
            $table->dropColumn('answer');
        });
        
        Schema::table('questions', function (Blueprint $table) {
            $table->json('answer')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('questions', function (Blueprint $table) {
            $table->foreignId('exam_id')->nullable()->constrained('exams')->cascadeOnDelete();
            
            $table->dropForeign(['lesson_id']);
            $table->dropColumn('lesson_id');
            
            $table->dropForeign(['classroom_id']);
            $table->dropColumn('classroom_id');
            
            $table->dropColumn('type');
            $table->dropColumn('difficulty');
            
            $table->dropColumn('answer');
        });
        
        Schema::table('questions', function (Blueprint $table) {
            $table->integer('answer')->nullable();
        });
    }
};
