-- ============================================
-- MIGRACIÓN: 03_create_scheduled_messages
-- Fecha: 2026-02-03
-- Descripción: Crear tabla y vista para sistema de mensajes programados/recordatorios
--              Permite programar envío de plantillas WhatsApp en fechas/horas específicas
-- Nota: Usa IF NOT EXISTS / OR REPLACE - Es seguro ejecutar múltiples veces
-- ============================================

-- Tabla para mensajes programados y recordatorios
CREATE TABLE IF NOT EXISTS scheduled_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    template_id INT NULL,
    template_name VARCHAR(100) NULL,
    template_language VARCHAR(10) DEFAULT 'es',
    template_parameters JSON NULL COMMENT 'Parámetros para las variables de la plantilla',
    message_type ENUM('text', 'template') DEFAULT 'template',
    message_content TEXT NULL COMMENT 'Contenido del mensaje si es tipo text',
    scheduled_date DATE NOT NULL,
    scheduled_time TIME NOT NULL,
    status ENUM('pending', 'sent', 'failed', 'cancelled') DEFAULT 'pending',
    sent_at DATETIME NULL,
    error_message TEXT NULL,
    created_by INT NULL COMMENT 'ID del admin que creó el recordatorio',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    
    INDEX idx_user_id (user_id),
    INDEX idx_scheduled_date (scheduled_date),
    INDEX idx_status (status),
    INDEX idx_scheduled_datetime (scheduled_date, scheduled_time, status),
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Vista para facilitar consultas con información del usuario
CREATE OR REPLACE VIEW scheduled_messages_view AS
SELECT 
    sm.*,
    u.name as user_name,
    u.phone_number,
    mt.name as template_display_name,
    mt.body_text as template_body,
    mt.status as template_status
FROM scheduled_messages sm
LEFT JOIN users u ON sm.user_id = u.id
LEFT JOIN message_templates mt ON sm.template_id = mt.id
ORDER BY sm.scheduled_date DESC, sm.scheduled_time DESC;
