<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Remove foreign keys if they exist (using identified names)
        try {
            Schema::table('jugador_equipo', function (Blueprint $table) {
                // Try standard name and then the ibfk one
                $table->dropForeign('jugador_equipo_id_jugador_foreign');
            });
        } catch (\Exception $e) {}

        try {
            // Drop confirmed name
            DB::statement('ALTER TABLE jugador_equipo DROP FOREIGN KEY jugador_equipo_ibfk_1');
        } catch (\Exception $e) {}

        try {
            DB::statement('ALTER TABLE qr_codes DROP FOREIGN KEY qr_codes_ibfk_2');
        } catch (\Exception $e) {}

        // 2. Increase the length of id_jugador in the main table
        Schema::table('jugadores', function (Blueprint $table) {
            $table->string('id_jugador', 20)->change();
        });

        // 3. Increase the length in referencing tables
        Schema::table('pases', function (Blueprint $table) {
            $table->string('id_jugador', 20)->change();
        });

        Schema::table('jugador_equipo', function (Blueprint $table) {
            $table->string('id_jugador', 20)->change();
        });

        Schema::table('qr_codes', function (Blueprint $table) {
            $table->string('id_jugador', 20)->nullable()->change();
        });

        // 4. Restore foreign keys (Laravel will pick names)
        Schema::table('pases', function (Blueprint $table) {
            // Check if column exists and is not already a FK
            try {
                $table->foreign('id_jugador')->references('id_jugador')->on('jugadores')->onDelete('cascade');
            } catch (\Exception $e) {}
        });

        Schema::table('jugador_equipo', function (Blueprint $table) {
            $table->foreign('id_jugador')->references('id_jugador')->on('jugadores')->onDelete('cascade');
        });

        Schema::table('qr_codes', function (Blueprint $table) {
            $table->foreign('id_jugador')->references('id_jugador')->on('jugadores')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // No revert needed for length increase
    }
};
