// 이메일 발송 (nodemailer)
// .env 에 SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS / SMTP_FROM 설정 필요

import nodemailer from "nodemailer";
import type { Transporter } from "nodemailer";
import { execute } from "./db";
import { createObjectId } from "./utils";

let cachedTransporter: Transporter | null = null;

function getTransporter(): Transporter {
  if (cachedTransporter) return cachedTransporter;
  const host = process.env.SMTP_HOST;
  const port = Number(process.env.SMTP_PORT || 465);
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;
  if (!host || !user || !pass) {
    // 운영 전: 미설정 시 콘솔로만 찍고 동작 (개발 편의)
    cachedTransporter = nodemailer.createTransport({ jsonTransport: true });
    return cachedTransporter;
  }
  cachedTransporter = nodemailer.createTransport({
    host,
    port,
    secure: port === 465,
    auth: { user, pass },
  });
  return cachedTransporter;
}

export interface MailAttachment {
  filename: string;
  content: Buffer;
  contentType?: string;
}

export interface SendMailInput {
  to: string;
  subject: string;
  html: string;
  text?: string;
  attachments?: MailAttachment[];
  refType?: string;
  refObjid?: string;
}

export async function sendMail(input: SendMailInput): Promise<{ ok: boolean; error?: string }> {
  const from = process.env.SMTP_FROM || "모모유통 <noreply@momo.com>";
  const transporter = getTransporter();

  const logId = createObjectId();
  await execute(
    `INSERT INTO momo_mail_logs (objid, to_email, subject, body, ref_type, ref_objid, status, regdate)
     VALUES ($1, $2, $3, $4, $5, $6, 'PENDING', NOW())`,
    [logId, input.to, input.subject, input.html.slice(0, 4000),
     input.refType ?? null, input.refObjid ?? null]
  );

  try {
    const info = await transporter.sendMail({
      from,
      to: input.to,
      subject: input.subject,
      html: input.html,
      text: input.text,
      attachments: input.attachments?.map((a) => ({
        filename: a.filename,
        content: a.content,
        contentType: a.contentType,
      })),
    });
    await execute(
      `UPDATE momo_mail_logs SET status='SENT', sent_at=NOW() WHERE objid=$1`,
      [logId]
    );
    if (process.env.NODE_ENV !== "production") {
      console.log("[mailer] sent:", info.messageId || "(jsonTransport)");
    }
    return { ok: true };
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    await execute(
      `UPDATE momo_mail_logs SET status='FAILED', error_msg=$2 WHERE objid=$1`,
      [logId, msg]
    );
    console.error("[mailer] failed:", msg);
    return { ok: false, error: msg };
  }
}
