-- ============================================================================
-- AI Tactical Combat Arena 2D - Script de Creación de Base de Datos
-- Motor: PostgreSQL / MySQL / H2 compatible
-- ============================================================================

-- 1. TABLA: usuarios
-- Registra credenciales, nivel, estadísticas globales y rol/clase del jugador.
CREATE TABLE IF NOT EXISTS usuarios (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    nivel INT NOT NULL DEFAULT 1,
    experiencia INT NOT NULL DEFAULT 0,
    partidas_jugadas INT NOT NULL DEFAULT 0,
    partidas_ganadas INT NOT NULL DEFAULT 0,
    clase_personaje VARCHAR(30) NOT NULL DEFAULT 'GUERRERO',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- 2. TABLA: partidas_combate
-- Mantiene el estado en tiempo real de la sesión de batalla contra el jefe IA.
CREATE TABLE IF NOT EXISTS partidas_combate (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    usuario_id BIGINT NOT NULL,
    nombre_jefe VARCHAR(100) NOT NULL,
    tipo_jefe VARCHAR(50) NOT NULL DEFAULT 'DRAGON_SOMBRA',
    hp_max_heroe INT NOT NULL,
    hp_actual_heroe INT NOT NULL,
    mp_max_heroe INT NOT NULL,
    mp_actual_heroe INT NOT NULL,
    hp_max_jefe INT NOT NULL,
    hp_actual_jefe INT NOT NULL,
    turno_actual INT NOT NULL DEFAULT 1,
    pociones_hp_restantes INT NOT NULL DEFAULT 3,
    pociones_mp_restantes INT NOT NULL DEFAULT 2,
    en_defensa BOOLEAN NOT NULL DEFAULT FALSE,
    estado VARCHAR(30) NOT NULL DEFAULT 'EN_CURSO', -- EN_CURSO, VICTORIA, DERROTA, ABANDONADA
    dano_total_infligido INT NOT NULL DEFAULT 0,
    dano_total_recibido INT NOT NULL DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_partida_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios (id) ON DELETE CASCADE
);

-- 3. TABLA: historial_turnos
-- Registro transaccional inmutable turno a turno que une la acción del jugador,
-- los cálculos matemáticos de Java y la respuesta táctica devuelta por gpt-4o-mini.
CREATE TABLE IF NOT EXISTS historial_turnos (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    partida_id BIGINT NOT NULL,
    usuario_id BIGINT NOT NULL,
    numero_turno INT NOT NULL,
    accion_jugador VARCHAR(50) NOT NULL,
    payload_frontend TEXT NOT NULL,
    calculo_jugador TEXT NOT NULL,
    payload_ia TEXT NOT NULL,
    estado_combate_resultante TEXT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_historial_partida FOREIGN KEY (partida_id) REFERENCES partidas_combate (id) ON DELETE CASCADE,
    CONSTRAINT fk_historial_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios (id) ON DELETE CASCADE
);

-- 4. TABLA: auditoria_eventos_frontend
-- Telemetría de comportamiento: clics, apertura de modales, comandos tácticos
-- enviados en tiempo real desde el cliente HTML5/JS para trazabilidad y auditoría.
CREATE TABLE IF NOT EXISTS auditoria_eventos_frontend (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    usuario_id BIGINT,
    partida_id BIGINT,
    tipo_evento VARCHAR(100) NOT NULL,
    elemento_origen VARCHAR(150) NOT NULL,
    metadata_json TEXT,
    ip_origen VARCHAR(45),
    user_agent VARCHAR(255),
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_auditoria_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios (id) ON DELETE SET NULL,
    CONSTRAINT fk_auditoria_partida FOREIGN KEY (partida_id) REFERENCES partidas_combate (id) ON DELETE SET NULL
);

-- ============================================================================
-- ÍNDICES PARA ALTO RENDIMIENTO
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_usuarios_username ON usuarios (username);
CREATE INDEX IF NOT EXISTS idx_usuarios_email ON usuarios (email);

CREATE INDEX IF NOT EXISTS idx_partidas_usuario ON partidas_combate (usuario_id);
CREATE INDEX IF NOT EXISTS idx_partidas_estado ON partidas_combate (estado);

CREATE INDEX IF NOT EXISTS idx_turnos_partida ON historial_turnos (partida_id);
CREATE INDEX IF NOT EXISTS idx_turnos_partida_num ON historial_turnos (partida_id, numero_turno);
CREATE INDEX IF NOT EXISTS idx_turnos_usuario ON historial_turnos (usuario_id);

CREATE INDEX IF NOT EXISTS idx_auditoria_usuario ON auditoria_eventos_frontend (usuario_id);
CREATE INDEX IF NOT EXISTS idx_auditoria_partida ON auditoria_eventos_frontend (partida_id);
CREATE INDEX IF NOT EXISTS idx_auditoria_fecha ON auditoria_eventos_frontend (created_at);
