-- =====================================================================
-- Sistema de Retas Pádel Americano
-- Esquema de base de datos MySQL 8+
-- Importar completo en una base de datos vacía (utf8mb4).
-- =====================================================================

SET NAMES utf8mb4;
SET time_zone = '-06:00';

-- ---------------------------------------------------------------------
-- usuarios_admin: cuentas del panel de administración/organizador
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS usuarios_admin (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre          VARCHAR(100)    NOT NULL,
    email           VARCHAR(150)    NOT NULL UNIQUE,
    password_hash   VARCHAR(255)    NOT NULL,
    rol             ENUM('admin','organizador') NOT NULL DEFAULT 'organizador',
    activo          TINYINT(1)      NOT NULL DEFAULT 1,
    creado_en       DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- jugadores: cuenta global del jugador (participa en varios torneos)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS jugadores (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre          VARCHAR(100)    NOT NULL,
    whatsapp        VARCHAR(20)     NULL,
    email           VARCHAR(150)    NULL,
    password_hash   VARCHAR(255)    NULL,          -- NULL si sólo entra por código o Google
    google_id       VARCHAR(120)    NULL,           -- sub de Google, si se activa "Entrar con Google"
    avatar_url      VARCHAR(255)    NULL,
    categoria       VARCHAR(30)     NULL,           -- ej. "6a", "5b"
    codigo_acceso   VARCHAR(10)     NOT NULL UNIQUE, -- ej. EDG-27, se usa también para el QR
    activo          TINYINT(1)      NOT NULL DEFAULT 1,
    creado_en       DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uq_jugadores_email (email),
    UNIQUE KEY uq_jugadores_google (google_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- torneos: cada "reta"
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS torneos (
    id                      INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre                  VARCHAR(150)    NOT NULL,
    categoria               VARCHAR(30)     NULL,
    fecha                   DATE            NOT NULL,
    hora_inicio             TIME            NOT NULL,
    duracion_ronda_min      SMALLINT UNSIGNED NOT NULL DEFAULT 25,
    num_canchas             TINYINT UNSIGNED NOT NULL DEFAULT 4,
    num_rondas              TINYINT UNSIGNED NOT NULL DEFAULT 5,
    suma_juegos_partido     TINYINT UNSIGNED NOT NULL DEFAULT 6,   -- ej. 6 -> 6-0,5-1,4-2,3-3
    modo_puntuacion         ENUM('suma_favor','diferencia') NOT NULL DEFAULT 'suma_favor',
    desempate               VARCHAR(40)     NOT NULL DEFAULT 'punto_oro',
    equipos_semifinal       TINYINT UNSIGNED NULL,                  -- 0/NULL = sin fase final; 4 u 8 jugadores avanzan
    formato_final           ENUM('suma_juegos','set_normal') NOT NULL DEFAULT 'suma_juegos',
    estado                  ENUM('borrador','inscripciones','en_curso','finalizado') NOT NULL DEFAULT 'borrador',
    codigo_torneo           VARCHAR(10)     NOT NULL UNIQUE,        -- código corto para unirse / QR
    admin_id                INT UNSIGNED    NOT NULL,
    creado_en               DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    actualizado_en          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_torneos_admin FOREIGN KEY (admin_id) REFERENCES usuarios_admin(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- canchas: canchas disponibles para un torneo
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS canchas (
    id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    torneo_id   INT UNSIGNED    NOT NULL,
    numero      TINYINT UNSIGNED NOT NULL,
    nombre      VARCHAR(50)     NULL,
    orden       TINYINT UNSIGNED NOT NULL DEFAULT 0,
    CONSTRAINT fk_canchas_torneo FOREIGN KEY (torneo_id) REFERENCES torneos(id) ON DELETE CASCADE,
    UNIQUE KEY uq_cancha_torneo_numero (torneo_id, numero)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- torneo_jugadores: inscripción de un jugador a un torneo concreto
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS torneo_jugadores (
    id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    torneo_id           INT UNSIGNED    NOT NULL,
    jugador_id          INT UNSIGNED    NOT NULL,
    estado              ENUM('activo','baja') NOT NULL DEFAULT 'activo',
    veces_descanso      SMALLINT UNSIGNED NOT NULL DEFAULT 0,   -- para repartir descansos parejo
    inscrito_en         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_tj_torneo FOREIGN KEY (torneo_id) REFERENCES torneos(id) ON DELETE CASCADE,
    CONSTRAINT fk_tj_jugador FOREIGN KEY (jugador_id) REFERENCES jugadores(id) ON DELETE CASCADE,
    UNIQUE KEY uq_torneo_jugador (torneo_id, jugador_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- rondas: una ronda de un torneo (fase grupos, semifinal o final)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS rondas (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    torneo_id       INT UNSIGNED    NOT NULL,
    numero          TINYINT UNSIGNED NOT NULL,       -- 1..num_rondas dentro de su fase
    fase            ENUM('grupos','semifinal','final') NOT NULL DEFAULT 'grupos',
    hora_estimada   TIME            NULL,
    estado          ENUM('pendiente','en_curso','finalizada') NOT NULL DEFAULT 'pendiente',
    creado_en       DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_rondas_torneo FOREIGN KEY (torneo_id) REFERENCES torneos(id) ON DELETE CASCADE,
    UNIQUE KEY uq_ronda_torneo_fase_num (torneo_id, fase, numero)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- partidos: un partido (cancha) dentro de una ronda
-- equipo A = jugador_a1 + jugador_a2 ; equipo B = jugador_b1 + jugador_b2
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS partidos (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ronda_id        INT UNSIGNED    NOT NULL,
    cancha_id       INT UNSIGNED    NULL,
    jugador_a1      INT UNSIGNED    NOT NULL,
    jugador_a2      INT UNSIGNED    NOT NULL,
    jugador_b1      INT UNSIGNED    NOT NULL,
    jugador_b2      INT UNSIGNED    NOT NULL,
    juegos_a        TINYINT UNSIGNED NULL,
    juegos_b        TINYINT UNSIGNED NULL,
    estado          ENUM('pendiente','jugando','finalizado') NOT NULL DEFAULT 'pendiente',
    hora_inicio     DATETIME        NULL,
    hora_fin        DATETIME        NULL,
    actualizado_en  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_partidos_ronda  FOREIGN KEY (ronda_id)   REFERENCES rondas(id)   ON DELETE CASCADE,
    CONSTRAINT fk_partidos_cancha FOREIGN KEY (cancha_id)  REFERENCES canchas(id)  ON DELETE SET NULL,
    CONSTRAINT fk_partidos_ja1 FOREIGN KEY (jugador_a1) REFERENCES jugadores(id),
    CONSTRAINT fk_partidos_ja2 FOREIGN KEY (jugador_a2) REFERENCES jugadores(id),
    CONSTRAINT fk_partidos_jb1 FOREIGN KEY (jugador_b1) REFERENCES jugadores(id),
    CONSTRAINT fk_partidos_jb2 FOREIGN KEY (jugador_b2) REFERENCES jugadores(id),
    INDEX idx_partidos_ronda (ronda_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- ronda_descansos: jugadores que descansan en una ronda (no caben en las canchas)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS ronda_descansos (
    id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ronda_id    INT UNSIGNED NOT NULL,
    jugador_id  INT UNSIGNED NOT NULL,
    CONSTRAINT fk_desc_ronda   FOREIGN KEY (ronda_id)   REFERENCES rondas(id) ON DELETE CASCADE,
    CONSTRAINT fk_desc_jugador FOREIGN KEY (jugador_id) REFERENCES jugadores(id) ON DELETE CASCADE,
    UNIQUE KEY uq_descanso (ronda_id, jugador_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- participaciones: una fila por jugador por partido ya jugado.
-- Desnormalizada a propósito: permite calcular clasificación y
-- estadísticas (compañero más frecuente, rival más frecuente, rachas)
-- con consultas simples y rápidas.
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS participaciones (
    id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    partido_id          INT UNSIGNED    NOT NULL,
    torneo_id           INT UNSIGNED    NOT NULL,   -- desnormalizado para agregaciones rápidas
    ronda_id            INT UNSIGNED    NOT NULL,
    jugador_id          INT UNSIGNED    NOT NULL,
    companero_id        INT UNSIGNED    NOT NULL,
    rival1_id           INT UNSIGNED    NOT NULL,
    rival2_id           INT UNSIGNED    NOT NULL,
    equipo              ENUM('A','B')   NOT NULL,
    juegos_favor        TINYINT UNSIGNED NOT NULL,
    juegos_contra       TINYINT UNSIGNED NOT NULL,
    gano                TINYINT(1)      NOT NULL DEFAULT 0,
    empato              TINYINT(1)      NOT NULL DEFAULT 0,
    puntos_obtenidos    SMALLINT        NOT NULL DEFAULT 0,  -- según modo_puntuacion del torneo
    creado_en           DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_part_partido   FOREIGN KEY (partido_id)   REFERENCES partidos(id)  ON DELETE CASCADE,
    CONSTRAINT fk_part_torneo    FOREIGN KEY (torneo_id)    REFERENCES torneos(id)   ON DELETE CASCADE,
    CONSTRAINT fk_part_ronda     FOREIGN KEY (ronda_id)     REFERENCES rondas(id)    ON DELETE CASCADE,
    CONSTRAINT fk_part_jugador   FOREIGN KEY (jugador_id)   REFERENCES jugadores(id) ON DELETE CASCADE,
    CONSTRAINT fk_part_companero FOREIGN KEY (companero_id) REFERENCES jugadores(id),
    CONSTRAINT fk_part_rival1    FOREIGN KEY (rival1_id)    REFERENCES jugadores(id),
    CONSTRAINT fk_part_rival2    FOREIGN KEY (rival2_id)    REFERENCES jugadores(id),
    UNIQUE KEY uq_participacion (partido_id, jugador_id),
    INDEX idx_part_torneo_jugador (torneo_id, jugador_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- sesiones_jugador: tokens de sesión simples para la PWA (sin cookies de servidor de terceros)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS sesiones_jugador (
    token           CHAR(64)        NOT NULL PRIMARY KEY,
    jugador_id      INT UNSIGNED    NOT NULL,
    creado_en       DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    expira_en       DATETIME        NOT NULL,
    CONSTRAINT fk_sesion_jugador FOREIGN KEY (jugador_id) REFERENCES jugadores(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------------------------------------------------------------------
-- Cuenta de administrador inicial de ejemplo.
-- Usuario: admin@retas.local  /  Contraseña: cambiar123
-- Cambia el correo y la contraseña apenas instales el sistema
-- (Panel admin -> por ahora edítalo directo en la base de datos con
--  password_hash('tu_password', PASSWORD_BCRYPT) desde un script PHP).
-- ---------------------------------------------------------------------
INSERT INTO usuarios_admin (nombre, email, password_hash, rol)
VALUES (
    'Administrador',
    'admin@retas.local',
    '$2y$12$.DaMFfaQYqHgdKEdKAOrMulno6EZtE3563ZF2PfHQnncpxMmnJLNG', -- cambiar123
    'admin'
)
ON DUPLICATE KEY UPDATE email = email;
