import nodemailer from 'nodemailer';

// Accept either the Laravel-style MAIL_* naming or the legacy SMTP_* names.
// MAIL_* wins so the operator can paste their existing .env block straight
// in without renaming. MAIL_FROM_ADDRESS is the visible sender (Brevo /
// Sendinblue requires this to be a verified domain).
const HOST = process.env.MAIL_HOST || process.env.SMTP_HOST;
const PORT = process.env.MAIL_PORT || process.env.SMTP_PORT;
const USER = process.env.MAIL_USERNAME || process.env.SMTP_USER;
const PASS = process.env.MAIL_PASSWORD || process.env.SMTP_PASS;
const FROM = process.env.MAIL_FROM_ADDRESS || USER;
const FROM_NAME = process.env.MAIL_FROM_NAME || 'Gate Pass';
// Port 465 = implicit TLS. Anything else (587, 2525) = STARTTLS, which
// nodemailer negotiates automatically when `secure: false`. Brevo's
// SMTP relay on 2525 is STARTTLS.
const portNum = PORT ? Number(PORT) : 587;

const isSmtpConfigured = !!(HOST && PORT && USER && PASS);

const transporter = isSmtpConfigured
  ? nodemailer.createTransport({
      host: HOST,
      port: portNum,
      secure: portNum === 465,
      auth: { user: USER, pass: PASS },
    })
  : null;

// Boot-time visibility. Email sends fail *silently* (logged, not delivered)
// when SMTP isn't fully configured — surface the state at startup so a
// misconfigured deploy is obvious in the logs instead of a mystery
// "invite never arrived". NB: these are API-side vars — setting them in the
// web app's .env has no effect.
if (transporter) {
  console.log(`[MAIL] SMTP configured — host=${HOST} port=${portNum} from=${FROM}`);
} else {
  const missing = [
    !HOST && 'MAIL_HOST',
    !PORT && 'MAIL_PORT',
    !USER && 'MAIL_USERNAME',
    !PASS && 'MAIL_PASSWORD',
  ].filter(Boolean).join(', ');
  console.warn(`[MAIL] SMTP NOT configured — emails will be logged, not sent. Missing: ${missing}. Set these in the API .env.`);
}

// Optional inline attachments (CID-referenced). Pass a `cid` and reference
// it in the html as `<img src="cid:my-id">`. Embedding via CID is more
// reliable than hot-linking the uploads URL — Gmail and Outlook commonly
// block external images by default, but render inline CID attachments.
export interface MailAttachment {
  filename: string;
  content: Buffer;
  cid?: string;
  contentType?: string;
}

export async function sendMail(
  to: string,
  subject: string,
  html: string,
  options?: { attachments?: MailAttachment[] },
): Promise<void> {
  if (transporter) {
    await transporter.sendMail({
      from: FROM_NAME ? `"${FROM_NAME}" <${FROM}>` : FROM,
      to,
      subject,
      html,
      attachments: options?.attachments,
    });
  } else {
    console.log(`[DEV MAIL] To: ${to}`);
    console.log(`[DEV MAIL] Subject: ${subject}`);
    if (options?.attachments?.length) {
      console.log(`[DEV MAIL] Attachments: ${options.attachments.map((a) => a.filename).join(', ')}`);
    }
    console.log(`[DEV MAIL] Body: ${html}`);
  }
}

export async function sendOtpEmail(
  email: string,
  otp: string
): Promise<void> {
  const subject = `${otp} is your Gate Pass verification code`;
  const html = renderOtpEmail(otp);
  await sendMail(email, subject, html);
}

// Transactional email — table-based layout because Outlook + several Gmail
// clients still drop modern CSS. All styles inlined. Keep image-free so the
// message renders the same in privacy-mode inboxes.
function renderOtpEmail(otp: string): string {
  const escapedOtp = otp.replace(/[^0-9A-Za-z]/g, '');
  return `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Verification code</title>
  </head>
  <body style="margin:0;padding:0;background-color:#f4f5f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#1f2937;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f4f5f7;padding:32px 16px;">
      <tr>
        <td align="center">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:480px;background-color:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.05);">
            <!-- Brand header -->
            <tr>
              <td style="background-color:#2563eb;padding:24px 32px;text-align:left;">
                <table role="presentation" cellpadding="0" cellspacing="0" border="0">
                  <tr>
                    <td style="width:36px;height:36px;background-color:#ffffff;border-radius:8px;text-align:center;vertical-align:middle;color:#2563eb;font-weight:700;font-size:13px;line-height:36px;">GP</td>
                    <td style="padding-left:12px;color:#ffffff;font-size:16px;font-weight:600;letter-spacing:0.2px;">Gate Pass</td>
                  </tr>
                </table>
              </td>
            </tr>

            <!-- Body -->
            <tr>
              <td style="padding:36px 36px 24px 36px;">
                <p style="margin:0 0 8px 0;font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:1px;color:#6b7280;">Verification</p>
                <h1 style="margin:0 0 16px 0;font-size:22px;font-weight:700;color:#111827;line-height:1.3;">Sign in to Gate Pass</h1>
                <p style="margin:0 0 28px 0;font-size:14px;line-height:1.55;color:#4b5563;">Enter the code below to finish signing in. The code expires in 10 minutes and can only be used once.</p>

                <!-- OTP box -->
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                  <tr>
                    <td align="center" style="background-color:#f3f4f6;border:1px solid #e5e7eb;border-radius:12px;padding:24px;">
                      <div style="font-family:'SF Mono',Consolas,Menlo,monospace;font-size:34px;font-weight:700;letter-spacing:10px;color:#111827;">${escapedOtp}</div>
                    </td>
                  </tr>
                </table>

                <p style="margin:24px 0 0 0;font-size:13px;line-height:1.55;color:#6b7280;">If you didn't request this code, you can safely ignore this email — someone may have typed your address by mistake.</p>
              </td>
            </tr>

            <!-- Footer -->
            <tr>
              <td style="padding:20px 36px 28px 36px;border-top:1px solid #f3f4f6;background-color:#fafafa;">
                <p style="margin:0;font-size:12px;line-height:1.5;color:#9ca3af;text-align:center;">This is an automated message from Gate Pass. Replies are not monitored.</p>
              </td>
            </tr>
          </table>

          <p style="margin:16px 0 0 0;font-size:11px;color:#9ca3af;">@${new Date().getFullYear()} Gatepass</p>
        </td>
      </tr>
    </table>
  </body>
</html>`;
}
