<?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('events', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->string('title');
            $table->string('title_en')->nullable();
            $table->string('slug');
            $table->text('description')->nullable();
            $table->text('description_en')->nullable();
            $table->string('type', 30);
            $table->string('status', 30)->default('draft');
            $table->string('location_type', 20);
            $table->foreignId('facility_id')->nullable()->constrained('facilities')->nullOnDelete();
            $table->string('location_name')->nullable();
            $table->text('location_address')->nullable();
            $table->timestamp('starts_at');
            $table->timestamp('ends_at');
            $table->timestamp('registration_opens_at')->nullable();
            $table->timestamp('registration_closes_at')->nullable();
            $table->unsignedInteger('max_capacity')->nullable();
            $table->jsonb('form_fields')->default('[]');
            $table->jsonb('settings')->default('{}');
            $table->unsignedInteger('registrations_count')->default(0);
            $table->timestamp('published_at')->nullable();
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['academy_id', 'slug']);
            $table->index(['academy_id', 'status']);
            $table->index(['academy_id', 'starts_at']);
            $table->index(['academy_id', 'type']);
        });

        DB::statement("ALTER TABLE events ADD CONSTRAINT events_type_check CHECK (type IN ('tournament', 'camp', 'competition', 'open_day', 'workshop', 'friendly', 'exhibition', 'other'))");
        DB::statement("ALTER TABLE events ADD CONSTRAINT events_status_check CHECK (status IN ('draft', 'published', 'registration_closed', 'in_progress', 'completed', 'cancelled'))");
        DB::statement("ALTER TABLE events ADD CONSTRAINT events_location_type_check CHECK (location_type IN ('facility', 'external'))");
    }

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