-- ============================================================
-- quoERP — Historial de Auditoria
-- Migracion: 025_audit_log.sql (version corregida — tabla ya existe)
-- ============================================================
-- Agrega columnas e indices necesarios a audit_logs existente.
-- Todos los ADD COLUMN usan IF NOT EXISTS para ser idempotentes.
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ─────────────────────────────────────────────────────────────
-- Agregar columnas faltantes a audit_logs
-- ─────────────────────────────────────────────────────────────
ALTER TABLE audit_logs
    ADD COLUMN IF NOT EXISTS company_id   INT UNSIGNED  NOT NULL DEFAULT 0
        COMMENT 'Empresa propietaria del registro',
    ADD COLUMN IF NOT EXISTS user_id      INT UNSIGNED  DEFAULT NULL
        COMMENT 'Usuario que ejecuto la accion',
    ADD COLUMN IF NOT EXISTS user_name    VARCHAR(120)  DEFAULT NULL
        COMMENT 'Snapshot del nombre del usuario',
    ADD COLUMN IF NOT EXISTS action       VARCHAR(60)   NOT NULL DEFAULT 'unknown'
        COMMENT 'Accion: create, update, delete, approve, cancel, post, pay...',
    ADD COLUMN IF NOT EXISTS entity_type  VARCHAR(60)   NOT NULL DEFAULT ''
        COMMENT 'Entidad afectada: sale_invoice, journal_entry, employee...',
    ADD COLUMN IF NOT EXISTS entity_id    INT UNSIGNED  DEFAULT NULL
        COMMENT 'ID del registro afectado',
    ADD COLUMN IF NOT EXISTS entity_label VARCHAR(200)  DEFAULT NULL
        COMMENT 'Descripcion legible del registro (num. factura, nombre empleado...)',
    ADD COLUMN IF NOT EXISTS description  VARCHAR(500)  DEFAULT NULL
        COMMENT 'Descripcion de la accion en texto libre',
    ADD COLUMN IF NOT EXISTS old_values   TEXT          DEFAULT NULL
        COMMENT 'JSON con valores anteriores (campos clave)',
    ADD COLUMN IF NOT EXISTS new_values   TEXT          DEFAULT NULL
        COMMENT 'JSON con nuevos valores',
    ADD COLUMN IF NOT EXISTS ip_address   VARCHAR(45)   DEFAULT NULL,
    ADD COLUMN IF NOT EXISTS created_at   DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP;

-- ─────────────────────────────────────────────────────────────
-- Indices (MariaDB soporta ADD INDEX IF NOT EXISTS)
-- En MySQL 5.7 sin soporte IF NOT EXISTS: comentar si da error
-- y crearlos manualmente solo si no existen.
-- ─────────────────────────────────────────────────────────────
ALTER TABLE audit_logs
    ADD INDEX IF NOT EXISTS idx_company (company_id),
    ADD INDEX IF NOT EXISTS idx_user    (user_id),
    ADD INDEX IF NOT EXISTS idx_entity  (entity_type, entity_id),
    ADD INDEX IF NOT EXISTS idx_action  (action),
    ADD INDEX IF NOT EXISTS idx_created (created_at);

SET FOREIGN_KEY_CHECKS = 1;

-- ─────────────────────────────────────────────────────────────
-- FIN DE MIGRACION
-- ALTER: audit_logs — columnas e indices para historial de auditoria
-- ─────────────────────────────────────────────────────────────
