<?php

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

return new class extends Migration {
    public function up(): void
    {
        // Remove registros duplicados mantendo o menor id por chave composta
        // Compatível com MySQL/MariaDB. Ignorado silenciosamente em outros drivers.
        try {
            DB::statement(<<<SQL
            DELETE r1 FROM rounds r1
            JOIN rounds r2
            ON r1.inscription_id = r2.inscription_id
            AND r1.participant_id = r2.participant_id
            AND r1.event_id = r2.event_id
            AND r1.modality_id = r2.modality_id
            AND r1.number = r2.number
            AND r1.`group` = r2.`group`
            AND r1.id > r2.id
            SQL);
        } catch (\Throwable $e) {
            // Em drivers que não suportam a query acima (ex.: SQLite), apenas segue.
        }

        Schema::table('rounds', function (Blueprint $table) {
            // Garante unicidade por participante/inscrição/rodada/modalidade/evento/grupo
            $table->unique(
                ['inscription_id','participant_id','event_id','modality_id','number','group'],
                'rounds_unique_key'
            );
        });
    }

    public function down(): void
    {
        Schema::table('rounds', function (Blueprint $table) {
            $table->dropUnique('rounds_unique_key');
        });
    }
};