<?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
    {
        // Extend tournaments table
        Schema::table('tournaments', function (Blueprint $table) {
            // knockout | group_knockout
            $table->string('format')->default('knockout')->after('status');
            $table->unsignedTinyInteger('group_count')->default(4)->after('format');
            // group | knockout
            $table->string('current_phase')->default('group')->after('group_count');
            $table->unsignedTinyInteger('groups_per_advance')->default(2)->after('current_phase');
        });

        // Extend tournament_matches table
        Schema::table('tournament_matches', function (Blueprint $table) {
            // group | knockout
            $table->string('phase')->default('knockout')->after('match_number');
            // e.g. "A", "B", "C" for group stage; null for knockout
            $table->string('group_name')->nullable()->after('phase');
            $table->unsignedTinyInteger('score1')->nullable()->after('group_name');
            $table->unsignedTinyInteger('score2')->nullable()->after('score1');
            $table->string('status')->default('pending')->after('score2');
            // next match slot this winner feeds into
            $table->foreignId('next_match_id')->nullable()->after('status')
                  ->constrained('tournament_matches')->nullOnDelete();
            $table->boolean('next_match_slot')->nullable()->after('next_match_id'); // 0=player1, 1=player2
        });
    }

    public function down(): void
    {
        Schema::table('tournament_matches', function (Blueprint $table) {
            $table->dropConstrainedForeignId('next_match_id');
            $table->dropColumn(['phase','group_name','score1','score2','status','next_match_slot']);
        });
        Schema::table('tournaments', function (Blueprint $table) {
            $table->dropColumn(['format','group_count','current_phase','groups_per_advance']);
        });
    }
};
