<?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
    {
        if (! Schema::hasTable('championship_matches')) {
            return;
        }

        Schema::table('championship_matches', function (Blueprint $table) {
            if (! Schema::hasColumn('championship_matches', 'parent_match_id')) {
                $table->foreignId('parent_match_id')
                    ->nullable()
                    ->after('championship_id')
                    ->constrained('championship_matches')
                    ->nullOnDelete();
            }

            if (! Schema::hasColumn('championship_matches', 'court_id')) {
                $table->foreignId('court_id')
                    ->nullable()
                    ->after('team_b_id')
                    ->constrained('courts')
                    ->nullOnDelete();
            }

            if (! Schema::hasColumn('championship_matches', 'start_time')) {
                $table->time('start_time')->nullable()->after('match_date');
            }

            if (! Schema::hasColumn('championship_matches', 'end_time')) {
                $table->time('end_time')->nullable()->after('start_time');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('championship_matches')) {
            return;
        }

        Schema::table('championship_matches', function (Blueprint $table) {
            if (Schema::hasColumn('championship_matches', 'parent_match_id')) {
                $table->dropForeign(['parent_match_id']);
                $table->dropColumn('parent_match_id');
            }
            if (Schema::hasColumn('championship_matches', 'court_id')) {
                $table->dropForeign(['court_id']);
                $table->dropColumn('court_id');
            }
            if (Schema::hasColumn('championship_matches', 'start_time')) {
                $table->dropColumn('start_time');
            }
            if (Schema::hasColumn('championship_matches', 'end_time')) {
                $table->dropColumn('end_time');
            }
        });
    }
};
