<?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('waitlists', function (Blueprint $table) {
            $table->id();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('participant_id')->constrained('participants');
            $table->foreignId('training_group_id')->constrained('training_groups');
            $table->integer('position');
            $table->timestamp('requested_at');
            $table->timestamp('notified_at')->nullable();
            $table->timestamp('responded_at')->nullable();
            $table->string('response', 20)->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->foreignId('enrolled_enrollment_id')->nullable()->constrained('enrollments');
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->unique(['participant_id', 'training_group_id']);
            $table->index(['training_group_id', 'position']);
        });

        DB::statement("ALTER TABLE waitlists ADD CONSTRAINT waitlists_response_check CHECK (response IS NULL OR response IN ('accepted', 'declined', 'expired'))");
    }

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