-- ============================================================
-- Club Palestino CRM v2.0 - MODULO DE ELECCIONES
-- Reglamento completo con 5 elecciones simultaneas
-- ============================================================

CREATE TABLE IF NOT EXISTS elecciones (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    nombre          VARCHAR(200)     NOT NULL,
    tipo            ENUM('directorio_central','directorio_juvenil','rama_futbol','rama_tenis','rama_padel','otro') NOT NULL,
    periodo         VARCHAR(20)      NULL COMMENT '2026-2029',
    fecha_inicio    DATETIME         NOT NULL,
    fecha_fin       DATETIME         NOT NULL,
    estado          ENUM('configuracion','inscripcion_candidatos','votacion_abierta','votacion_cerrada','escrutinio','finalizada','cancelada') NOT NULL DEFAULT 'configuracion',
    max_lista       TINYINT UNSIGNED NOT NULL DEFAULT 7 COMMENT 'Max candidatos por lista',
    min_votos_indep TINYINT UNSIGNED NOT NULL DEFAULT 3 COMMENT 'Min candidatos indep a marcar',
    max_votos_indep TINYINT UNSIGNED NOT NULL DEFAULT 5 COMMENT 'Max candidatos indep a marcar',
    requiere_acciones TINYINT(1)     NOT NULL DEFAULT 0,
    acciones_varones INT UNSIGNED    NOT NULL DEFAULT 20,
    acciones_damas  INT UNSIGNED     NOT NULL DEFAULT 5,
    requiere_rama   TINYINT(1)       NOT NULL DEFAULT 0 COMMENT 'Solo inscritos en la rama',
    rama_nombre     VARCHAR(50)      NULL,
    indep_obligatorio TINYINT(1)     NOT NULL DEFAULT 1 COMMENT 'Debe haber candidatos independientes',
    edad_min        TINYINT UNSIGNED NULL,
    edad_max        TINYINT UNSIGNED NULL,
    notas           TEXT             NULL,
    created_at      TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Proceso electoral (agrupa varias elecciones en un mismo periodo)
CREATE TABLE IF NOT EXISTS proceso_electoral (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    nombre          VARCHAR(200)     NOT NULL,
    periodo         VARCHAR(20)      NOT NULL,
    fecha_inicio    DATETIME         NOT NULL,
    fecha_fin       DATETIME         NOT NULL,
    estado          ENUM('configuracion','inscripcion','votacion','escrutinio','finalizado') NOT NULL DEFAULT 'configuracion',
    reglamento_url  VARCHAR(500)     NULL,
    notas           TEXT             NULL,
    created_at      TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Vincular elecciones al proceso
ALTER TABLE elecciones ADD COLUMN IF NOT EXISTS proceso_id INT UNSIGNED NULL AFTER id;

-- TRICEL
CREATE TABLE IF NOT EXISTS eleccion_tricel (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    proceso_id      INT UNSIGNED     NOT NULL,
    socio_id        INT UNSIGNED     NOT NULL,
    cargo           ENUM('presidente','secretario','miembro') NOT NULL DEFAULT 'miembro',
    activo          TINYINT(1)       NOT NULL DEFAULT 1,
    PRIMARY KEY (id),
    KEY idx_proc_tricel (proceso_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Listas de candidatos
CREATE TABLE IF NOT EXISTS eleccion_listas (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    eleccion_id     INT UNSIGNED     NOT NULL,
    letra           CHAR(1)          NOT NULL COMMENT 'A, B, C...',
    nombre          VARCHAR(150)     NULL COMMENT 'Nombre opcional de la lista',
    apoderado_socio_id INT UNSIGNED  NULL,
    estado          ENUM('inscrita','aprobada','inhabilitada') NOT NULL DEFAULT 'inscrita',
    orden           TINYINT UNSIGNED NOT NULL DEFAULT 0,
    created_at      TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uk_lista_letra (eleccion_id,letra),
    KEY idx_elec_lista (eleccion_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Candidatos (en lista o independientes)
CREATE TABLE IF NOT EXISTS eleccion_candidatos (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    eleccion_id     INT UNSIGNED     NOT NULL,
    lista_id        INT UNSIGNED     NULL COMMENT 'NULL = independiente',
    socio_id        INT UNSIGNED     NOT NULL,
    nombre          VARCHAR(150)     NOT NULL,
    rut             VARCHAR(12)      NOT NULL,
    cargo_postulado VARCHAR(50)      NULL,
    orden_cedula    TINYINT UNSIGNED NOT NULL DEFAULT 0,
    es_independiente TINYINT(1)      NOT NULL DEFAULT 0,
    estado          ENUM('inscrito','aprobado','inhabilitado','retirado') NOT NULL DEFAULT 'inscrito',
    documentos_url  VARCHAR(500)     NULL,
    notas           TEXT             NULL,
    votos_recibidos INT UNSIGNED     NOT NULL DEFAULT 0,
    created_at      TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_elec_cand (eleccion_id,lista_id),
    KEY idx_socio_cand (socio_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Padron electoral (socios habilitados para votar)
CREATE TABLE IF NOT EXISTS eleccion_padron (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    eleccion_id     INT UNSIGNED     NOT NULL,
    socio_id        INT UNSIGNED     NOT NULL,
    nombre          VARCHAR(150)     NOT NULL,
    rut             VARCHAR(12)      NOT NULL,
    genero          ENUM('M','F')    NULL,
    acciones        INT UNSIGNED     NOT NULL DEFAULT 0,
    habilitado      TINYINT(1)       NOT NULL DEFAULT 1,
    motivo_inhabil  VARCHAR(200)     NULL,
    ya_voto         TINYINT(1)       NOT NULL DEFAULT 0,
    voto_at         TIMESTAMP        NULL,
    codigo_2fa      VARCHAR(8)       NULL,
    codigo_2fa_expira DATETIME       NULL,
    intentos_2fa    TINYINT UNSIGNED NOT NULL DEFAULT 0,
    PRIMARY KEY (id),
    UNIQUE KEY uk_padron (eleccion_id,socio_id),
    KEY idx_rut_padron (rut)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Votos (encriptados - no vinculables al socio)
CREATE TABLE IF NOT EXISTS eleccion_votos (
    id              BIGINT UNSIGNED  NOT NULL AUTO_INCREMENT,
    eleccion_id     INT UNSIGNED     NOT NULL,
    numero_voto     INT UNSIGNED     NOT NULL COMMENT 'Correlativo por eleccion',
    voto_lista_id   INT UNSIGNED     NULL COMMENT 'NULL = voto en blanco para listas',
    voto_hash       VARCHAR(64)      NOT NULL COMMENT 'SHA256 para auditoria',
    es_blanco       TINYINT(1)       NOT NULL DEFAULT 0,
    timestamp       TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_elec_voto (eleccion_id),
    UNIQUE KEY uk_voto_num (eleccion_id,numero_voto)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Votos a candidatos individuales (independientes)
CREATE TABLE IF NOT EXISTS eleccion_votos_individuales (
    id              BIGINT UNSIGNED  NOT NULL AUTO_INCREMENT,
    voto_id         BIGINT UNSIGNED  NOT NULL,
    candidato_id    INT UNSIGNED     NOT NULL,
    PRIMARY KEY (id),
    KEY idx_voto_ind (voto_id),
    KEY idx_cand_ind (candidato_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Registro de sesion de votacion (para auditoria - sin vincular al voto)
CREATE TABLE IF NOT EXISTS eleccion_sesiones (
    id              BIGINT UNSIGNED  NOT NULL AUTO_INCREMENT,
    proceso_id      INT UNSIGNED     NOT NULL,
    socio_id        INT UNSIGNED     NOT NULL,
    ip              VARCHAR(45)      NULL,
    user_agent      VARCHAR(500)     NULL,
    metodo_auth     ENUM('rut_2fa','carnet_2fa','pasaporte_2fa') NOT NULL,
    numeros_voto    JSON             NULL COMMENT '{"dir_central":123,"juvenil":456,...}',
    timestamp       TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_proc_ses (proceso_id,socio_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Resultados finales
CREATE TABLE IF NOT EXISTS eleccion_resultados (
    id              INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    eleccion_id     INT UNSIGNED     NOT NULL,
    tipo            ENUM('lista','independiente') NOT NULL,
    lista_id        INT UNSIGNED     NULL,
    candidato_id    INT UNSIGNED     NULL,
    votos           INT UNSIGNED     NOT NULL DEFAULT 0,
    porcentaje      DECIMAL(5,2)     NOT NULL DEFAULT 0,
    electo          TINYINT(1)       NOT NULL DEFAULT 0,
    PRIMARY KEY (id),
    KEY idx_elec_res (eleccion_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

