/**
 * Alert Notification Channels
 * Email (SMTP via nodemailer), future Slack support
 */
const nodemailer = require('nodemailer');

let _transporter = null;

function getTransporter() {
  if (_transporter) return _transporter;

  const host = process.env.SMTP_HOST;
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;

  if (!host || !user || !pass) {
    console.warn('[Alerts] SMTP not configured (SMTP_HOST, SMTP_USER, SMTP_PASS). Email alerts disabled.');
    return null;
  }

  _transporter = nodemailer.createTransport({
    host,
    port: parseInt(process.env.SMTP_PORT) || 587,
    secure: process.env.SMTP_SECURE === 'true',
    auth: { user, pass }
  });

  return _transporter;
}

/**
 * Send email alert
 * @param {string} to - Recipient email
 * @param {string} subject - Email subject
 * @param {string} html - HTML body
 */
async function sendEmail(to, subject, html) {
  const transporter = getTransporter();
  if (!transporter) {
    console.log(`[Alerts] Email skipped (SMTP not configured): ${subject}`);
    return false;
  }

  try {
    await transporter.sendMail({
      from: process.env.SMTP_FROM || process.env.SMTP_USER,
      to,
      subject: `[BI-CCC Alert] ${subject}`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <div style="background: #7600BE; color: white; padding: 16px 24px; border-radius: 8px 8px 0 0;">
            <h2 style="margin: 0; font-size: 18px;">BI-CCC Alert</h2>
          </div>
          <div style="padding: 24px; border: 1px solid #E8EAED; border-top: none; border-radius: 0 0 8px 8px;">
            ${html}
          </div>
          <p style="font-size: 11px; color: #9AA0A6; text-align: center; margin-top: 12px;">
            CambioReal BI - Central Command Center
          </p>
        </div>
      `
    });
    console.log(`[Alerts] Email sent: ${subject} -> ${to}`);
    return true;
  } catch (err) {
    console.error(`[Alerts] Email failed: ${err.message}`);
    return false;
  }
}

/**
 * Send Slack notification (future — ready when webhook URL is available)
 */
async function sendSlack(webhook, message, severity) {
  if (!webhook) return false;

  const colorMap = { P0: '#D93025', P1: '#E8710A', P2: '#1A73E8' };
  try {
    const resp = await fetch(webhook, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        attachments: [{
          color: colorMap[severity] || '#1A73E8',
          title: `[${severity}] BI-CCC Alert`,
          text: message,
          footer: 'CambioReal BI-CCC',
          ts: Math.floor(Date.now() / 1000)
        }]
      })
    });
    return resp.ok;
  } catch (err) {
    console.error(`[Alerts] Slack failed: ${err.message}`);
    return false;
  }
}

module.exports = { sendEmail, sendSlack };
