<?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
    {
        Schema::create('training_sessions', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('training_group_id')->constrained('training_groups');
            $table->foreignId('schedule_id')->nullable()->constrained('training_schedules');
            $table->unsignedBigInteger('facility_id')->nullable(); // FK added in Phase 5
            $table->date('session_date');
            $table->time('start_time');
            $table->time('end_time');
            $table->foreignId('trainer_id')->nullable()->constrained('users');
            $table->foreignId('assistant_trainer_id')->nullable()->constrained('users');
            $table->text('substitute_reason')->nullable();
            $table->integer('session_number')->default(1);
            $table->string('topic')->nullable();
            $table->text('objectives')->nullable();
            $table->string('status', 20)->default('scheduled');
            $table->text('cancelled_reason')->nullable();
            $table->foreignId('cancelled_by')->nullable()->constrained('users');
            $table->unsignedBigInteger('rescheduled_to_id')->nullable();
            $table->string('weather_condition', 20)->nullable();
            $table->time('actual_start_time')->nullable();
            $table->time('actual_end_time')->nullable();
            $table->integer('expected_participants')->default(0);
            $table->integer('actual_participants')->nullable();
            $table->text('notes')->nullable();
            $table->text('incident_notes')->nullable();
            $table->jsonb('equipment_used')->default('[]');
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->index(['academy_id', 'session_date']);
            $table->index(['training_group_id', 'session_date']);
            $table->index(['academy_id', 'status']);
            $table->index('trainer_id');

            $table->foreign('rescheduled_to_id')->references('id')->on('training_sessions')->nullOnDelete();
        });

        DB::statement("ALTER TABLE training_sessions ADD CONSTRAINT training_sessions_status_check CHECK (status IN ('scheduled', 'in_progress', 'completed', 'cancelled', 'rescheduled'))");
    }

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