-- ============================================================
--  AUDITORÍA NOTAS DE ENFERMERÍA — CLÍNICA SION
--  Base de datos MySQL
-- ============================================================

CREATE DATABASE IF NOT EXISTS auditoria_sion
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE auditoria_sion;

-- ------------------------------------------------------------
-- Pacientes analizados
-- ------------------------------------------------------------
CREATE TABLE pacientes (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cc              VARCHAR(20)  NOT NULL,
    nombre          VARCHAR(160) NOT NULL,
    fecha_analisis  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    archivo_pdf     VARCHAR(255) NOT NULL,
    total_notas     INT UNSIGNED NOT NULL DEFAULT 0,
    total_hallazgos INT UNSIGNED NOT NULL DEFAULT 0,
    usuario_id      INT UNSIGNED NOT NULL,
    FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB;

-- ------------------------------------------------------------
-- Hallazgos por nota
-- ------------------------------------------------------------
CREATE TABLE hallazgos (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    paciente_id     INT UNSIGNED NOT NULL,
    id_nota         VARCHAR(20)  NOT NULL,
    profesional     VARCHAR(160) NOT NULL,
    fecha_grabacion DATE         NOT NULL,
    hora_grabacion  TIME         NOT NULL,
    ampm_grabacion  CHAR(2)      NOT NULL,
    fecha_atencion  DATE         NULL,
    hora_atencion   TIME         NULL,
    ampm_atencion   CHAR(2)      NULL,
    r1_ok           TINYINT(1)   NOT NULL DEFAULT 1,
    r2_ok           TINYINT(1)   NOT NULL DEFAULT 1,
    r3_ok           TINYINT(1)   NOT NULL DEFAULT 1,
    r1_detalle      VARCHAR(255) NULL,
    r2_detalle      VARCHAR(255) NULL,
    r3_detalle      VARCHAR(255) NULL,
    num_hallazgos   TINYINT      NOT NULL DEFAULT 0,
    estado          ENUM('OK','HALLAZGO') NOT NULL DEFAULT 'OK',
    FOREIGN KEY (paciente_id) REFERENCES pacientes(id) ON DELETE CASCADE,
    INDEX idx_paciente (paciente_id),
    INDEX idx_estado   (estado)
) ENGINE=InnoDB;

-- ------------------------------------------------------------
-- Log de accesos
-- ------------------------------------------------------------
CREATE TABLE log_accesos (
    id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    usuario_id  INT UNSIGNED NOT NULL,
    ip          VARCHAR(45)  NOT NULL,
    accion      VARCHAR(80)  NOT NULL,
    fecha       DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB;
