<?php

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

return new class extends Migration
{
    public function up(): void
    {
        foreach (['students', 'enrollments', 'student_promotion_records'] as $table) {
            if (!Schema::hasTable($table)) {
                continue;
            }
            Schema::table($table, function (Blueprint $t) use ($table) {
                if (!Schema::hasColumn($table, 'lifecycle_mode')) {
                    $t->string('lifecycle_mode', 20)->default('legacy');
                }
                if (!Schema::hasColumn($table, 'lifecycle_policy_version')) {
                    $t->string('lifecycle_policy_version', 30)->default('legacy_v1');
                }
            });
        }

        if (!Schema::hasTable('section_placement_batches')) {
            Schema::create('section_placement_batches', function (Blueprint $table) {
                $table->id();
                $table->string('from_school_year', 25);
                $table->string('to_school_year', 25);
                $table->unsignedInteger('from_grade_level_id')->nullable();
                $table->unsignedInteger('to_grade_level_id')->nullable();
                $table->unsignedInteger('section_capacity_used');
                $table->unsignedInteger('total_students')->default(0);
                $table->unsignedInteger('section_count')->default(0);
                $table->string('algorithm', 100)->default('score_band_balanced_v1');
                $table->json('configuration_snapshot_json')->nullable();
                $table->json('preview_snapshot_json')->nullable();
                $table->unsignedInteger('created_by')->nullable();
                $table->unsignedInteger('finalized_by')->nullable();
                $table->dateTime('finalized_at')->nullable();
                $table->string('status', 30)->default('draft');
                $table->timestamps();
                $table->index(['from_school_year', 'to_school_year', 'status'], 'placement_batches_year_status_idx');
            });
        }

        if (!Schema::hasTable('section_placement_batch_students')) {
            Schema::create('section_placement_batch_students', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('batch_id');
                $table->unsignedInteger('student_id');
                $table->string('student_type', 30);
                $table->unsignedInteger('source_decision_id')->nullable();
                $table->unsignedInteger('source_enrollment_id')->nullable();
                $table->decimal('final_score', 6, 2)->nullable();
                $table->decimal('placement_score', 6, 2)->nullable();
                $table->string('score_band', 1);
                $table->string('placement_band_reason', 60);
                $table->unsignedInteger('planned_section_index')->nullable();
                $table->unsignedInteger('assigned_section_id')->nullable();
                $table->unsignedInteger('assignment_order')->default(0);
                $table->boolean('was_override')->default(false);
                $table->text('override_reason')->nullable();
                $table->dateTime('created_at')->nullable();
                $table->unique(['batch_id', 'student_id'], 'placement_batch_student_unique');
                $table->index(['student_id', 'assigned_section_id'], 'placement_batch_student_assignment_idx');
            });
        }

        if (Schema::hasTable('configuration')) {
            $exists = DB::table('configuration')->where('config_key', 'promotion.section_capacity')->exists();
            if (!$exists) {
                DB::table('configuration')->insert([
                    'config_key' => 'promotion.section_capacity',
                    'config_value' => '20',
                ]);
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('section_placement_batch_students');
        Schema::dropIfExists('section_placement_batches');
    }
};
