/**
 * Email Service — Layanan pengiriman email notifikasi menggunakan Nodemailer.
 * Konfigurasi SMTP diambil dari tabel settings di database secara dinamis.
 */
const nodemailer = require('nodemailer');
const { logger } = require('nodejs-log-agent');
const db = require('../models');

/**
 * Mengambil semua setting email dari database dan mengembalikan objek konfigurasi.
 */
async function getEmailConfig() {
  const settings = await db.setting.findAll({
    where: { group: 'email' }
  });

  const config = {};
  settings.forEach(s => {
    config[s.key] = s.value;
  });

  return config;
}

/**
 * Membuat transporter Nodemailer berdasarkan konfigurasi dari database.
 */
async function createTransporter() {
  const config = await getEmailConfig();

  if (config.email_notification_enabled !== 'true') {
    return null; // Notifikasi email dinonaktifkan
  }

  if (!config.email_smtp_host || !config.email_smtp_user || !config.email_smtp_pass) {
    logger.warn('[Email] Konfigurasi SMTP tidak lengkap. Notifikasi email tidak akan dikirim.');
    return null;
  }

  const transporter = nodemailer.createTransport({
    host: config.email_smtp_host,
    port: parseInt(config.email_smtp_port || '587', 10),
    secure: config.email_smtp_secure === 'true',
    auth: {
      user: config.email_smtp_user,
      pass: config.email_smtp_pass
    },
    tls: {
      rejectUnauthorized: false // Untuk kompatibilitas dengan self-signed cert
    }
  });

  return { transporter, config };
}

/**
 * Mengirim email notifikasi ketika terjadi auto-skip invoice.
 * @param {Array} skippedInvoices - Daftar invoice yang di-skip
 * @param {number} thresholdHours - Batas jam yang dikonfigurasi
 */
async function sendAutoSkipNotification(skippedInvoices, thresholdHours) {
  try {
    const result = await createTransporter();
    if (!result) return; // Notifikasi dinonaktifkan atau config tidak lengkap

    const { transporter, config } = result;
    const recipient = config.email_admin_recipient;
    const fromName = config.email_from_name || 'WaBill System';
    const fromEmail = config.email_smtp_user;

    if (!recipient) {
      logger.warn('[Email] Email penerima admin tidak dikonfigurasi.');
      return;
    }

    const now = new Date().toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' });
    const invoiceRows = skippedInvoices.map(inv => `
      <tr>
        <td style="padding: 8px 12px; border-bottom: 1px solid #f0f0f0;">${inv.inv_id}</td>
        <td style="padding: 8px 12px; border-bottom: 1px solid #f0f0f0;">${inv.inv_name || 'N/A'}</td>
        <td style="padding: 8px 12px; border-bottom: 1px solid #f0f0f0;">${inv.inv_type || 'N/A'}</td>
        <td style="padding: 8px 12px; border-bottom: 1px solid #f0f0f0;">${inv.phoneNumber || 'N/A'}</td>
        <td style="padding: 8px 12px; border-bottom: 1px solid #f0f0f0; color: #dc2626;">${new Date(inv.createdAt).toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' })}</td>
      </tr>
    `).join('');

    const htmlContent = `
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: 'Segoe UI', Arial, sans-serif; background-color: #f8fafc;">
  <div style="max-width: 680px; margin: 30px auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08);">
    
    <!-- Header -->
    <div style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); padding: 32px 40px;">
      <div style="display: flex; align-items: center; gap: 16px;">
        <div style="width: 48px; height: 48px; background: rgba(255,255,255,0.2); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
          <span style="font-size: 24px;">⏭️</span>
        </div>
        <div>
          <h1 style="margin: 0; color: #ffffff; font-size: 22px; font-weight: 700;">Auto-Skip Invoice Alert</h1>
          <p style="margin: 4px 0 0; color: rgba(255,255,255,0.85); font-size: 14px;">Notifikasi Sistem WaBill</p>
        </div>
      </div>
    </div>

    <!-- Body -->
    <div style="padding: 32px 40px;">
      <div style="background: #fffbeb; border: 1px solid #fde68a; border-radius: 8px; padding: 16px 20px; margin-bottom: 24px;">
        <p style="margin: 0; color: #92400e; font-size: 14px; font-weight: 500;">
          ⚠️ Sistem telah otomatis men-skip <strong>${skippedInvoices.length} invoice</strong> yang telah pending lebih dari <strong>${thresholdHours} jam</strong>.
        </p>
        <p style="margin: 8px 0 0; color: #b45309; font-size: 13px;">Waktu: ${now} WIB</p>
      </div>

      <h2 style="margin: 0 0 16px; font-size: 16px; color: #374151; font-weight: 600;">Daftar Invoice yang Di-skip:</h2>
      
      <div style="overflow-x: auto; border-radius: 8px; border: 1px solid #e5e7eb;">
        <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
          <thead>
            <tr style="background: #f9fafb;">
              <th style="padding: 10px 12px; text-align: left; font-weight: 600; color: #6b7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;">ID Invoice</th>
              <th style="padding: 10px 12px; text-align: left; font-weight: 600; color: #6b7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;">Nama</th>
              <th style="padding: 10px 12px; text-align: left; font-weight: 600; color: #6b7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;">Jenis</th>
              <th style="padding: 10px 12px; text-align: left; font-weight: 600; color: #6b7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;">No. HP</th>
              <th style="padding: 10px 12px; text-align: left; font-weight: 600; color: #6b7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;">Dibuat Pada</th>
            </tr>
          </thead>
          <tbody>
            ${invoiceRows}
          </tbody>
        </table>
      </div>

      <div style="margin-top: 24px; padding: 16px; background: #f0fdf4; border-radius: 8px; border: 1px solid #bbf7d0;">
        <p style="margin: 0; color: #166534; font-size: 13px;">
          💡 <strong>Tip:</strong> Invoice yang di-skip dapat dilihat dan di-queue ulang melalui halaman <em>Skipped Invoices</em> di dashboard admin.
        </p>
      </div>
    </div>

    <!-- Footer -->
    <div style="padding: 20px 40px; background: #f9fafb; border-top: 1px solid #e5e7eb;">
      <p style="margin: 0; color: #9ca3af; font-size: 12px; text-align: center;">
        Email ini dikirim otomatis oleh WaBill System. Jangan balas email ini.
      </p>
    </div>
  </div>
</body>
</html>
    `;

    const mailOptions = {
      from: `"${fromName}" <${fromEmail}>`,
      to: recipient,
      subject: `[WaBill] ⏭️ ${skippedInvoices.length} Invoice Di-skip Otomatis — ${now}`,
      html: htmlContent
    };

    await transporter.sendMail(mailOptions);
    logger.info(`[Email] Notifikasi auto-skip berhasil dikirim ke ${recipient} untuk ${skippedInvoices.length} invoice.`);

  } catch (error) {
    // Jangan lempar error — kegagalan email tidak boleh menghentikan proses utama
    logger.error(`[Email] Gagal mengirim notifikasi auto-skip: ${error.message}`, {
      message: error.message,
      stack: error.stack
    });
  }
}

/**
 * Test koneksi SMTP dengan konfigurasi yang diberikan.
 * @param {Object} smtpConfig - Konfigurasi SMTP untuk di-test
 */
async function testSmtpConnection(smtpConfig) {
  const transporter = nodemailer.createTransport({
    host: smtpConfig.host,
    port: parseInt(smtpConfig.port || '587', 10),
    secure: smtpConfig.secure === true || smtpConfig.secure === 'true',
    auth: {
      user: smtpConfig.user,
      pass: smtpConfig.pass
    },
    tls: { rejectUnauthorized: false }
  });

  await transporter.verify();
  return true;
}

module.exports = {
  sendAutoSkipNotification,
  testSmtpConnection
};
