<?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('championship_matches', function (Blueprint $table) {
            $table->id();
            $table->foreignId('championship_id')->constrained('championships')->cascadeOnDelete();

            $table->foreignId('group_id')->nullable()->constrained('championship_groups')->nullOnDelete();

            $table->foreignId('team_a_id')->constrained('championship_teams')->cascadeOnDelete();
            $table->foreignId('team_b_id')->constrained('championship_teams')->cascadeOnDelete();

            $table->foreignId('court_id')->constrained('courts')->cascadeOnDelete();

            $table->date('match_date');
            $table->time('start_time');
            $table->time('end_time');

            $table->unsignedTinyInteger('stage')->default(1);  // 1 group, 2 knockout
            $table->unsignedTinyInteger('status')->default(1); // 1 scheduled
            $table->string('round', 50)->nullable(); // e.g. group_round_1, quarter_final, semi_final, final

            $table->foreignId('winner_team_id')->nullable()->constrained('championship_teams')->nullOnDelete();
            $table->timestamps();

            $table->index(['championship_id', 'match_date']);
            $table->index(['championship_id', 'stage']);
            $table->index('group_id');
            $table->index('status');
            $table->index(['court_id', 'match_date', 'start_time', 'end_time'], 'cm_court_date_time_idx');
        });
    }

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

