-- Migration: Tournament Bracket System
-- Tabellen für 32-Spieler Single Elimination Turnier mit Platz 3

-- Turnier-Teilnehmer mit Seeding
CREATE TABLE IF NOT EXISTS tournament_participants (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    tournament_id INT UNSIGNED NOT NULL,
    spieler_id INT UNSIGNED NOT NULL,
    spieler_name VARCHAR(100) NOT NULL,
    elo_at_registration INT DEFAULT 1000,
    seed_position INT UNSIGNED NULL,
    registered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_reserve TINYINT(1) DEFAULT 0,
    UNIQUE KEY uk_tournament_spieler (tournament_id, spieler_id),
    INDEX idx_tournament (tournament_id),
    INDEX idx_seed (tournament_id, seed_position)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Turnier-Matches (Bracket)
CREATE TABLE IF NOT EXISTS tournament_matches (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    tournament_id INT UNSIGNED NOT NULL,
    match_number INT UNSIGNED NOT NULL,
    round INT UNSIGNED NOT NULL,
    round_name VARCHAR(50) NOT NULL,
    best_of INT UNSIGNED NOT NULL DEFAULT 3,
    player1_id INT UNSIGNED NULL,
    player2_id INT UNSIGNED NULL,
    player1_score INT UNSIGNED DEFAULT 0,
    player2_score INT UNSIGNED DEFAULT 0,
    winner_id INT UNSIGNED NULL,
    next_match_id INT UNSIGNED NULL,
    is_third_place TINYINT(1) DEFAULT 0,
    status ENUM('pending', 'ready', 'in_progress', 'completed') DEFAULT 'pending',
    played_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_tournament_match (tournament_id, match_number),
    INDEX idx_tournament_round (tournament_id, round),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Bracket-Konfiguration pro Turnier
ALTER TABLE tournaments 
    ADD COLUMN IF NOT EXISTS bracket_generated TINYINT(1) DEFAULT 0,
    ADD COLUMN IF NOT EXISTS seeding_mode ENUM('elo', 'random') DEFAULT 'elo',
    ADD COLUMN IF NOT EXISTS bracket_type ENUM('single_elimination', 'double_elimination') DEFAULT 'single_elimination';
