const nodemailer = require('nodemailer');

/**
 * Builds HTML/text mail body from ticket form data for the receiver.
 * @param {Object} formData - { subject, ticket_type_name, description, user_name, user_email, created_at, recipient_email_display, sender_email_display, ... }
 * @returns {string} HTML body
 */
function buildTicketMailBody(formData) {
  const lines = [];
  lines.push(`<h2>New Support Ticket</h2>`);
  lines.push(`<div style="background:#f0f4f8; padding:10px 12px; border-radius:6px; margin-bottom:14px;">`);
  lines.push(`<p style="margin:4px 0;"><strong>Receiver (To):</strong> ${escapeHtml(formData.recipient_email_display || '')} — <em>who receives this email</em></p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Sender (From):</strong> ${escapeHtml(formData.sender_email_display || 'SAT Support')} — <em>system address that sent this email</em></p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Raised by (Reporter):</strong> ${escapeHtml(formData.user_name || '')} (${escapeHtml(formData.user_email || '')}) — <em>who reported the issue</em></p>`);
  lines.push(`</div>`);
  lines.push(`<p><strong>Subject:</strong> ${escapeHtml(formData.subject || 'No subject')}</p>`);
  lines.push(`<p><strong>Ticket Type:</strong> ${escapeHtml(formData.ticket_type_name || '')}</p>`);
  lines.push(`<p><strong>Date:</strong> ${escapeHtml(formData.created_at || new Date().toISOString())}</p>`);
  lines.push(`<hr/>`);
  lines.push(`<h3>Issue Details</h3>`);
  lines.push(`<p>${escapeHtml(formData.description || '').replace(/\n/g, '<br/>')}</p>`);
  if (formData.extra_fields && typeof formData.extra_fields === 'object') {
    lines.push(`<h3>Additional Information</h3><ul>`);
    for (const [key, value] of Object.entries(formData.extra_fields)) {
      if (value != null && value !== '') {
        lines.push(`<li><strong>${escapeHtml(String(key))}:</strong> ${escapeHtml(String(value))}</li>`);
      }
    }
    lines.push(`</ul>`);
  }
  lines.push(`<hr/><p><em>This is an automated message from the SAT Ticketing System.</em></p>`);
  return lines.join('\n');
}

/**
 * Builds HTML mail body for "ticket resolved" notification.
 * @param {Object} ticket - Ticket object with id, subject, ticket_type_name, user_name, user_email, created_at, closed_at, recipient_email, etc.
 * @returns {string} HTML body
 */
function buildCloseTicketMailBody(ticket) {
  const lines = [];
  lines.push(`<h2>Ticket Resolved</h2>`);
  lines.push(`<p>The following support ticket has been resolved.</p>`);
  lines.push(`<div style="background:#f0f4f8; padding:10px 12px; border-radius:6px; margin-bottom:14px;">`);
  lines.push(`<p style="margin:4px 0;"><strong>Ticket ID:</strong> #${escapeHtml(String(ticket.id || ''))}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Subject:</strong> ${escapeHtml(ticket.subject || 'No subject')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Type:</strong> ${escapeHtml(ticket.ticket_type_name || '')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Raised by:</strong> ${escapeHtml(ticket.user_name || '')} (${escapeHtml(ticket.user_email || '')})</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Created:</strong> ${escapeHtml(ticket.created_at ? new Date(ticket.created_at).toLocaleString() : '-')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Resolved:</strong> ${escapeHtml(ticket.closed_at ? new Date(ticket.closed_at).toLocaleString() : '-')}</p>`);
  lines.push(`</div>`);
  lines.push(`<p><em>This is an automated notification from the SAT Ticketing System.</em></p>`);
  return lines.join('\n');
}

function escapeHtml(text) {
  if (text == null) return '';
  const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
  return String(text).replace(/[&<>"']/g, (m) => map[m]);
}

/**
 * Build HTML for audit assignment email (when an audit is scheduled and assigned to a user).
 * @param {Object} data - { auditName, scheduledDate, recurrenceType, assignedToName, createdByName }
 */
function buildAuditAssignmentMailBody(data) {
  const lines = [];
  lines.push(`<h2>Audit Scheduled – You Have Been Assigned</h2>`);
  lines.push(`<p>Hello ${escapeHtml(data.assignedToName || 'there')},</p>`);
  lines.push(`<p>An audit has been scheduled and assigned to you.</p>`);
  lines.push(`<div style="background:#f0f4f8; padding:12px 16px; border-radius:8px; margin:14px 0;">`);
  lines.push(`<p style="margin:4px 0;"><strong>Audit:</strong> ${escapeHtml(data.auditName || '')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Scheduled date:</strong> ${escapeHtml(data.scheduledDate || '')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Recurrence:</strong> ${escapeHtml(data.recurrenceType || 'One-time')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Scheduled by:</strong> ${escapeHtml(data.createdByName || '')}</p>`);
  lines.push(`</div>`);
  lines.push(`<p>Please complete the audit by the scheduled date.</p>`);
  lines.push(`<hr/><p><em>This is an automated message from the SAT Audit Scheduling system.</em></p>`);
  return lines.join('\n');
}

/**
 * Build HTML for audit reminder email (X days before the scheduled date).
 * @param {Object} data - { auditName, scheduledDate, daysUntil, assignedToName }
 */
function buildAuditReminderMailBody(data) {
  const lines = [];
  lines.push(`<h2>Audit Reminder</h2>`);
  lines.push(`<p>Hello ${escapeHtml(data.assignedToName || 'there')},</p>`);
  lines.push(`<p>This is a reminder that you have an audit scheduled${data.daysUntil ? ` in ${data.daysUntil} day(s).` : '.'}</p>`);
  lines.push(`<div style="background:#f0f4f8; padding:12px 16px; border-radius:8px; margin:14px 0;">`);
  lines.push(`<p style="margin:4px 0;"><strong>Audit:</strong> ${escapeHtml(data.auditName || '')}</p>`);
  lines.push(`<p style="margin:4px 0;"><strong>Scheduled date:</strong> ${escapeHtml(data.scheduledDate || '')}</p>`);
  lines.push(`</div>`);
  lines.push(`<p>Please ensure the audit is completed on or before the scheduled date.</p>`);
  lines.push(`<hr/><p><em>This is an automated reminder from the SAT Audit Scheduling system.</em></p>`);
  return lines.join('\n');
}

function isSmtpEnabled() {
  const flag = String(process.env.SMTP_ENABLED ?? 'true').trim().toLowerCase();
  return flag !== 'false' && flag !== '0' && flag !== 'no';
}

function smtpAuthHint(err) {
  if (err?.code !== 'EAUTH') return err?.message || 'Email send failed';
  return (
    'SMTP login rejected (EAUTH). For Gmail use an App Password with 2-Step Verification enabled — ' +
    'not your normal account password. Set SMTP_USER to the Gmail address and SMTP_PASS to the 16-character app password. ' +
    'Or set SMTP_ENABLED=false in SAT_backend/.env to skip email in local dev.'
  );
}

/**
 * Sends ticket notification email to the recipient.
 * Uses SMTP from env (SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS). If not set, logs and skips.
 * @param {Object} opts - { to, subject, htmlBody, fromEmail, attachments }
 * @param {Array} opts.attachments - Optional array of { filename, content: Buffer }
 * @returns {Promise<{ sent?: boolean, skipped?: boolean, error?: string, code?: string, reason?: string }>}
 */
async function sendTicketEmail({ to, subject, htmlBody, fromEmail, attachments }) {
  if (!isSmtpEnabled()) {
    console.warn('[emailService] SMTP_ENABLED=false. Skipping send. To:', to, 'Subject:', subject);
    return { skipped: true, reason: 'SMTP_ENABLED=false' };
  }

  const host = (process.env.SMTP_HOST || '').trim();
  const port = Number(process.env.SMTP_PORT || 587);
  const user = (process.env.SMTP_USER || '').trim();
  const pass = (process.env.SMTP_PASS || '').trim().replace(/\s+/g, ''); // Gmail App Password: no spaces

  if (!host || !user || !pass) {
    console.warn('[emailService] SMTP not configured (SMTP_HOST/USER/PASS). Skipping send. To:', to, 'Subject:', subject);
    return { skipped: true, reason: 'SMTP not configured' };
  }

  const transporter = nodemailer.createTransport({
    host,
    port,
    secure: port === 465,
    auth: { user, pass }
  });

  const from = fromEmail || process.env.SMTP_FROM || user;
  const mailOptions = {
    from,
    to,
    subject: subject || 'New Support Ticket',
    html: htmlBody
  };
  if (attachments && attachments.length > 0) {
    mailOptions.attachments = attachments.map((a) => ({
      filename: a.filename || 'attachment',
      content: Buffer.isBuffer(a.content) ? a.content : Buffer.from(a.content)
    }));
  }

  try {
    await transporter.sendMail(mailOptions);
    return { sent: true };
  } catch (err) {
    const error = smtpAuthHint(err);
    console.error('[emailService] Failed to send email:', error);
    return { sent: false, error, code: err.code || null };
  }
}

module.exports = {
  buildTicketMailBody,
  buildCloseTicketMailBody,
  buildAuditAssignmentMailBody,
  buildAuditReminderMailBody,
  sendTicketEmail
};
