<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('class_schedule_exceptions', function (Blueprint $table) {
            $table->id()->comment('主鍵');

            $table->foreignId('venue_id')
                ->constrained('venues')
                ->cascadeOnDelete()
                ->comment('場館');

            // schedule_id：若是針對「既有每週循環課表」做異動/停課，請填入
            // 若是「加開課程」或「休館（全日/時段）」可留空
            $table->foreignId('schedule_id')
                ->nullable()
                ->constrained('class_schedules')
                ->nullOnDelete()
                ->comment('原課表');

            $table->date('date')->comment('日期');

            // action：異動類型
            // - cancel：停課（取消既有課表）
            // - override：異動（改時間/課程/教練等）
            // - add：加開（新增一堂）
            // - close：休館（全日或時段）
            $table->string('action', 20)->comment('動作');

            // 時段：override/add/close(時段休館) 使用；cancel/全日休館可為空
            $table->time('start_time')->nullable()->comment('開始');
            $table->time('end_time')->nullable()->comment('結束');

            // 課程/教練：override/add 使用
            $table->string('class_title', 150)->nullable()->comment('課程');
            $table->foreignId('coach_id')
                ->nullable()
                ->constrained('coaches')
                ->nullOnDelete()
                ->comment('教練');
            $table->string('coach_display_name', 100)->nullable()->comment('教練名');

            $table->string('location', 100)->nullable()->comment('地點');
            $table->string('level', 50)->nullable()->comment('程度');
            $table->string('note', 255)->nullable()->comment('備註');

            $table->unsignedInteger('sort_order')->default(0)->comment('排序');
            $table->boolean('is_active')->default(true)->comment('啟用');

            $table->timestamp('created_at')->nullable()->comment('建立');
            $table->timestamp('updated_at')->nullable()->comment('更新');
            $table->timestamp('deleted_at')->nullable()->comment('刪除');

            // 同一週循環課表在同一天通常只會有一筆異動
            $table->unique(['schedule_id', 'date']);
            $table->index(['venue_id', 'date']);
            $table->index(['date', 'action']);
        });
    }

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