<?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_groups', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('program_id')->constrained('training_programs');
            $table->foreignId('branch_id')->constrained('branches');
            $table->string('name');
            $table->string('name_ar');
            $table->string('code', 10);
            $table->foreignId('head_trainer_id')->nullable()->constrained('users');
            $table->integer('max_capacity')->default(20);
            $table->integer('current_count')->default(0);
            $table->integer('waitlist_count')->default(0);
            $table->string('season', 50)->nullable();
            $table->date('start_date')->nullable();
            $table->date('end_date')->nullable();
            $table->string('status', 20)->default('forming');
            $table->timestamp('status_changed_at')->nullable();
            $table->text('notes')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['academy_id', 'code']);
            $table->index(['academy_id', 'status']);
            $table->index(['academy_id', 'program_id']);
            $table->index('head_trainer_id');
        });

        DB::statement("ALTER TABLE training_groups ADD CONSTRAINT training_groups_status_check CHECK (status IN ('forming', 'active', 'full', 'on_hold', 'completed', 'cancelled'))");
    }

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