-- WireAdmin Phase 10: SaaS Multi-Tenant

-- Module Catalog
CREATE TABLE IF NOT EXISTS wa_module_catalog (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    slug VARCHAR(50) NOT NULL UNIQUE,
    description TEXT,
    monthly_price INT NOT NULL, -- Price in CLP
    icon VARCHAR(50),
    is_active BOOLEAN DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Company Active Modules (Subscriptions)
CREATE TABLE IF NOT EXISTS wa_company_modules (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company_id INT NOT NULL,
    module_id INT NOT NULL,
    status ENUM('active', 'suspended', 'cancelled') DEFAULT 'active',
    activated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at DATE,
    last_payment_date DATE,
    FOREIGN KEY (company_id) REFERENCES wa_companies(id) ON DELETE CASCADE,
    FOREIGN KEY (module_id) REFERENCES wa_module_catalog(id) ON DELETE CASCADE,
    UNIQUE KEY unique_company_module (company_id, module_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Purchase History
CREATE TABLE IF NOT EXISTS wa_purchases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company_id INT NOT NULL,
    module_id INT NOT NULL,
    amount INT NOT NULL,
    flow_token VARCHAR(255),
    flow_order VARCHAR(255),
    status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP NULL,
    FOREIGN KEY (company_id) REFERENCES wa_companies(id) ON DELETE CASCADE,
    FOREIGN KEY (module_id) REFERENCES wa_module_catalog(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Seed Module Catalog
INSERT INTO wa_module_catalog (name, slug, description, monthly_price, icon) VALUES
('Contabilidad', 'accounting', 'Plan de cuentas, libro diario, mayor e informes financieros', 29990, '📊'),
('Facturación', 'billing', 'Gestión de facturas, boletas, clientes y reportes de ventas', 39990, '🧾'),
('RRHH Básico', 'hr_basic', 'Empleados, contratos, cálculo de remuneraciones y liquidaciones', 34990, '👔'),
('RRHH Avanzado', 'hr_advanced', 'Control de asistencia, vacaciones y documentos legales', 24990, '⏰'),
('SII Integration', 'sii', 'Certificados digitales, generación y firma de DTE', 49990, '🔐')
ON DUPLICATE KEY UPDATE name=VALUES(name);
