<?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('space_reservations', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('facility_id')->constrained('facilities');
            $table->foreignId('space_layout_id')->nullable()->constrained('space_layouts')->nullOnDelete();
            $table->string('status', 20)->default('confirmed');
            $table->date('reservation_date');
            $table->time('start_time');
            $table->time('end_time');
            $table->jsonb('segment_ids')->default('[]');
            $table->nullableMorphs('reservable');
            $table->string('title', 255)->nullable();
            $table->text('notes')->nullable();
            $table->boolean('is_recurring')->default(false);
            $table->string('recurrence_pattern', 50)->nullable();
            $table->date('recurrence_end_date')->nullable();
            $table->foreignId('created_by')->constrained('users');
            $table->foreignId('cancelled_by')->nullable()->constrained('users');
            $table->timestamp('cancelled_at')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->index(['facility_id', 'reservation_date', 'status']);
            $table->index(['academy_id', 'reservation_date']);
            // nullableMorphs already creates index on (reservable_type, reservable_id)
        });

        DB::statement("ALTER TABLE space_reservations ADD CONSTRAINT space_reservations_status_check CHECK (status IN ('confirmed', 'tentative', 'cancelled'))");
    }

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