-- ============================================================
-- quoERP — Notificaciones mejoradas + alertas de vencimiento
-- Migracion: 024_notifications_enhanced.sql
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- Enriquecer la tabla de notificaciones con campos adicionales
ALTER TABLE notifications
    ADD COLUMN IF NOT EXISTS icon        VARCHAR(40)  DEFAULT NULL
        COMMENT 'Icono Tabler (ej: ti-alert-triangle)',
    ADD COLUMN IF NOT EXISTS color       VARCHAR(20)  DEFAULT NULL
        COMMENT 'Color CSS (ej: var(--red), var(--ora))',
    ADD COLUMN IF NOT EXISTS action_url  VARCHAR(255) DEFAULT NULL
        COMMENT 'URL de accion al hacer clic en la notificacion',
    ADD COLUMN IF NOT EXISTS source_type VARCHAR(40)  DEFAULT NULL
        COMMENT 'Tipo de documento origen: cxc, cxp, sale_invoice, purchase_order...',
    ADD COLUMN IF NOT EXISTS source_id   INT UNSIGNED DEFAULT NULL
        COMMENT 'ID del registro origen',
    ADD COLUMN IF NOT EXISTS priority    TINYINT UNSIGNED NOT NULL DEFAULT 1
        COMMENT '1=info, 2=warning, 3=critical';

-- Indice para deduplicacion rapida
ALTER TABLE notifications
    ADD INDEX IF NOT EXISTS idx_source (source_type, source_id, type, user_id);

-- Tabla de configuracion de umbrales de alertas por empresa
CREATE TABLE IF NOT EXISTS notification_settings (
    id                 INT UNSIGNED NOT NULL AUTO_INCREMENT,
    company_id         INT UNSIGNED NOT NULL,
    cxc_days_warning   TINYINT UNSIGNED NOT NULL DEFAULT 7
        COMMENT 'Dias antes del vencimiento para alertar CxC',
    cxc_days_critical  TINYINT UNSIGNED NOT NULL DEFAULT 3
        COMMENT 'Dias antes del vencimiento para alerta critica CxC',
    cxp_days_warning   TINYINT UNSIGNED NOT NULL DEFAULT 7
        COMMENT 'Dias antes del vencimiento para alertar CxP',
    cxp_days_critical  TINYINT UNSIGNED NOT NULL DEFAULT 3
        COMMENT 'Dias antes del vencimiento para alerta critica CxP',
    notify_roles       VARCHAR(200) DEFAULT 'admin,gerente,finanzas'
        COMMENT 'Role slugs que reciben notificaciones (CSV)',
    last_checked_at    DATETIME     DEFAULT NULL
        COMMENT 'Ultima vez que se ejecuto la verificacion automatica',
    created_at         DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at         DATETIME     DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uk_company (company_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

SET FOREIGN_KEY_CHECKS = 1;

-- ─────────────────────────────────────────────────────────────
-- FIN DE MIGRACION
-- ALTER: notifications (icon, color, action_url, source_type, source_id, priority)
-- Tabla nueva: notification_settings
-- ─────────────────────────────────────────────────────────────
