<?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_layouts', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('facility_id')->constrained('facilities')->cascadeOnDelete();
            $table->string('name', 255);
            $table->string('name_ar', 255);
            $table->string('layout_type', 20);
            $table->jsonb('layout_config')->default('{}');
            $table->boolean('is_recurring')->default(true);
            $table->smallInteger('effective_day_of_week')->nullable();
            $table->date('effective_date')->nullable();
            $table->time('start_time');
            $table->time('end_time');
            $table->boolean('is_active')->default(true);
            $table->integer('sort_order')->default(0);
            $table->jsonb('metadata')->default('{}');
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();

            $table->index(['facility_id', 'is_recurring', 'effective_day_of_week']);
            $table->index(['facility_id', 'effective_date']);
            $table->index(['academy_id', 'is_active']);
        });

        DB::statement("ALTER TABLE space_layouts ADD CONSTRAINT space_layouts_layout_type_check CHECK (layout_type IN ('grid', 'lanes', 'zones', 'custom'))");
        DB::statement("ALTER TABLE space_layouts ADD CONSTRAINT space_layouts_day_of_week_check CHECK (effective_day_of_week IS NULL OR effective_day_of_week BETWEEN 0 AND 6)");

        Schema::create('space_segments', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('space_layout_id')->constrained('space_layouts')->cascadeOnDelete();
            $table->string('code', 20);
            $table->string('name', 100);
            $table->string('name_ar', 100);
            $table->integer('row_index')->nullable();
            $table->integer('col_index')->nullable();
            $table->integer('lane_number')->nullable();
            $table->decimal('area_sqm', 8, 2)->nullable();
            $table->boolean('is_available')->default(true);
            $table->integer('capacity')->nullable();
            $table->integer('sort_order')->default(0);
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->unique(['space_layout_id', 'code']);
            $table->index(['space_layout_id', 'is_available']);
        });
    }

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