-- Sistema de Mensajería Discord & Telegram
-- Base de datos: lastwar2

CREATE DATABASE IF NOT EXISTS lastwar2 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE lastwar2;

-- 1. Usuarios del sistema
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    role ENUM('user', 'admin') DEFAULT 'user',
    telegram_chat_id VARCHAR(50) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_username (username)
) ENGINE=InnoDB;

-- 2. Destinatarios
CREATE TABLE IF NOT EXISTS recipients (
    id INT AUTO_INCREMENT PRIMARY KEY,
    platform_id BIGINT NOT NULL,
    name VARCHAR(255) NOT NULL,
    type ENUM('channel', 'user') NOT NULL,
    platform ENUM('discord', 'telegram') NOT NULL,
    language_code VARCHAR(10) DEFAULT 'es',
    chat_mode VARCHAR(20) DEFAULT 'agent',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_platform_recipient (platform, platform_id),
    INDEX idx_platform (platform),
    INDEX idx_type (type)
) ENGINE=InnoDB;

-- 3. Contenido de mensajes
CREATE TABLE IF NOT EXISTS messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user (user_id)
) ENGINE=InnoDB;

-- 4. Programaciones de envío
CREATE TABLE IF NOT EXISTS schedules (
    id INT AUTO_INCREMENT PRIMARY KEY,
    message_id INT NOT NULL,
    recipient_id INT NOT NULL,
    send_time DATETIME NOT NULL,
    status ENUM('draft', 'pending', 'processing', 'sent', 'failed', 'cancelled', 'disabled') DEFAULT 'pending',
    is_recurring BOOLEAN DEFAULT FALSE,
    recurring_days VARCHAR(50) NULL,
    recurring_time TIME NULL,
    sent_at DATETIME NULL,
    error_message TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_status (status),
    INDEX idx_send_time (send_time),
    INDEX idx_message (message_id),
    INDEX idx_recipient (recipient_id)
) ENGINE=InnoDB;

-- 5. Plantillas de mensajes recurrentes
CREATE TABLE IF NOT EXISTS recurrent_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    message_content TEXT NOT NULL,
    telegram_command VARCHAR(50) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_command (telegram_command)
) ENGINE=InnoDB;

-- 6. Mensajes enviados (historial)
CREATE TABLE IF NOT EXISTS sent_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    schedule_id INT NOT NULL,
    recipient_id INT NOT NULL,
    platform_message_id VARCHAR(100) NULL,
    message_count INT DEFAULT 1,
    sent_at DATETIME NOT NULL,
    user_id INT NULL,
    INDEX idx_sent_at (sent_at)
) ENGINE=InnoDB;

-- 7. Idiomas soportados para traducción
CREATE TABLE IF NOT EXISTS supported_languages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    language_code VARCHAR(10) NOT NULL,
    language_name VARCHAR(50) NOT NULL,
    flag_emoji VARCHAR(10) DEFAULT '',
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_lang_code (language_code)
) ENGINE=InnoDB;

-- 8. Configuración de mensaje de bienvenida Telegram
CREATE TABLE IF NOT EXISTS telegram_bot_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    message_text TEXT,
    button_text VARCHAR(100) NULL,
    group_invite_link VARCHAR(500) NULL,
    is_active BOOLEAN DEFAULT TRUE,
    register_users BOOLEAN DEFAULT TRUE,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;

-- 9. Registro de interacciones de usuarios Telegram
CREATE TABLE IF NOT EXISTS telegram_bot_interactions (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    username VARCHAR(100) NULL,
    first_name VARCHAR(100) NULL,
    last_name VARCHAR(100) NULL,
    interaction_type VARCHAR(50) NOT NULL,
    interaction_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user (user_id),
    INDEX idx_date (interaction_date)
) ENGINE=InnoDB;

-- 10. Mensajes de bienvenida por grupo Telegram
CREATE TABLE IF NOT EXISTS telegram_welcome_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    chat_id BIGINT NOT NULL,
    welcome_message TEXT,
    button_text VARCHAR(100) NULL,
    group_invite_link VARCHAR(500) NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    language_code VARCHAR(10) DEFAULT 'es',
    language_name VARCHAR(50) DEFAULT 'Español',
    flag_emoji VARCHAR(10) DEFAULT '🇪🇸',
    UNIQUE KEY unique_chat_id (chat_id)
) ENGINE=InnoDB;

-- 11. Cola de traducciones
CREATE TABLE IF NOT EXISTS translation_queue (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    platform VARCHAR(20) NOT NULL,
    message_id BIGINT NULL,
    chat_id BIGINT NOT NULL,
    user_id BIGINT NULL,
    text_to_translate TEXT NOT NULL,
    source_lang VARCHAR(10) NOT NULL,
    target_lang VARCHAR(10) NULL,
    status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending',
    attempts INT DEFAULT 0,
    error_message TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    processed_at DATETIME NULL,
    INDEX idx_status (status),
    INDEX idx_created (created_at)
) ENGINE=InnoDB;

-- 12. Log de actividades
CREATE TABLE IF NOT EXISTS activity_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    username VARCHAR(50) NOT NULL,
    action VARCHAR(50) NOT NULL,
    details TEXT,
    timestamp DATETIME NOT NULL,
    INDEX idx_user (user_id),
    INDEX idx_timestamp (timestamp)
) ENGINE=InnoDB;

-- 13. Bloqueos de comandos
CREATE TABLE IF NOT EXISTS command_locks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    chat_id BIGINT NOT NULL,
    command VARCHAR(100) NOT NULL,
    type ENUM('command', 'translation') DEFAULT 'command',
    data JSON NULL,
    message_id BIGINT NULL,
    status ENUM('processing', 'completed', 'failed') DEFAULT 'processing',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at DATETIME NULL,
    INDEX idx_chat_command (chat_id, command),
    INDEX idx_status (status)
) ENGINE=InnoDB;

-- 14. Configuración general
CREATE TABLE IF NOT EXISTS settings (
    setting_key VARCHAR(100) PRIMARY KEY,
    setting_value TEXT
) ENGINE=InnoDB;

-- Insertar idiomas por defecto
INSERT INTO supported_languages (language_code, language_name, flag_emoji, is_active) VALUES
('es', 'Español', '🇪🇸', TRUE),
('en', 'English', '🇬🇧', TRUE),
('pt', 'Português', '🇧🇷', TRUE),
('fr', 'Français', '🇫🇷', TRUE),
('de', 'Deutsch', '🇩🇪', FALSE),
('it', 'Italiano', '🇮🇹', FALSE),
('ru', 'Русский', '🇷🇺', FALSE),
('zh', '中文', '🇨🇳', FALSE),
('ja', '日本語', '🇯🇵', FALSE),
('ko', '한국어', '🇰🇷', FALSE)
ON DUPLICATE KEY UPDATE language_name = VALUES(language_name);

-- Insertar configuración por defecto de Telegram
INSERT INTO telegram_bot_messages (id, message_text, button_text, is_active, register_users) VALUES
(1, '¡Hola {user_name}! 👋\n\nUsa /comandos para ver los comandos disponibles.\n\nTambién puedes usar /agente para interactuar con la IA.', 'Unirse al grupo', TRUE, TRUE)
ON DUPLICATE KEY UPDATE message_text = VALUES(message_text);

-- Insertar usuario admin (password: admin123)
INSERT INTO users (username, password, role) VALUES
('admin', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'admin')
ON DUPLICATE KEY UPDATE username = VALUES(username);

-- Insertar configuración inicial
INSERT INTO settings (setting_key, setting_value) VALUES
('app_name', 'Sistema de Mensajería'),
('default_language', 'es'),
('timezone', 'America/Mexico_City')
ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value);
