import nodemailer from "nodemailer";

type Notice = { type: "booking" | "contact"; payload: Record<string, unknown> };

export async function sendNotification(notice: Notice) {
  if (process.env.SMTP_PASSWORD) return sendWithSmtp(notice);
  if (process.env.RESEND_API_KEY) return sendWithResend(notice);
  return { sent: false, reason: "not_configured" };
}

async function sendWithSmtp(notice: Notice) {
  const user = process.env.SMTP_USER || "hello@nailsbyella.com";
  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST || "mail.nailsbyella.com",
    port: Number(process.env.SMTP_PORT || 465),
    secure: (process.env.SMTP_PORT || "465") === "465",
    auth: { user, pass: process.env.SMTP_PASSWORD },
  });
  await transporter.sendMail({
    from: process.env.SMTP_FROM || `Nails by Ella <${user}>`,
    to: process.env.BOOKING_NOTIFICATION_EMAIL || "hello@nailsbyella.com",
    replyTo: customerEmail(notice),
    subject: subject(notice),
    html: message(notice),
    text: plainText(notice),
  });
  return { sent: true, provider: "smtp" };
}

async function sendWithResend(notice: Notice) {
  const response = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ from: "Nails by Ella <bookings@nailsbyella.com>", to: [process.env.BOOKING_NOTIFICATION_EMAIL || "hello@nailsbyella.com"], reply_to: customerEmail(notice), subject: subject(notice), html: message(notice), text: plainText(notice) }),
  });
  if (!response.ok) throw new Error(`Email provider rejected notification (${response.status}).`);
  return { sent: true, provider: "resend" };
}

function customerEmail(notice: Notice) { return typeof notice.payload.email === "string" ? notice.payload.email : undefined; }
function value(notice: Notice, key: string, fallback = "Not provided") { const item = notice.payload[key]; return typeof item === "string" && item.trim() ? item.trim() : fallback; }
function subject(notice: Notice) { const name=value(notice,"name","Customer");return notice.type === "booking" ? `New appointment inquiry from ${name}` : `New website message from ${name}`; }

function message(notice: Notice) {
  const name=value(notice,"name","Customer");
  const email=value(notice,"email");
  const phone=value(notice,"phone");
  const isBooking=notice.type==="booking";
  const details=isBooking?[
    ["Service",value(notice,"service")],
    ["Preferred date",formatDate(value(notice,"preferredDate"))],
    ["Preferred time",formatTime(value(notice,"preferredTime"))],
    ["Phone",phone],
    ["Email",email],
  ]:[["Email",email]];
  const inspiration=value(notice,"inspirationLink","");
  const note=value(notice,isBooking?"message":"message");
  const rows=details.map(([label,item])=>`<tr><td style="padding:12px 16px;color:#8a7770;font-size:13px;border-bottom:1px solid #eee5e1;width:38%;">${escapeHtml(label)}</td><td style="padding:12px 16px;color:#2f2927;font-size:15px;font-weight:600;border-bottom:1px solid #eee5e1;">${escapeHtml(item)}</td></tr>`).join("");
  const inspirationBlock=isBooking&&inspiration?`<div style="margin-top:20px;"><p style="margin:0 0 8px;color:#8a7770;font-size:12px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;">Inspiration</p><a href="${escapeHtml(inspiration)}" style="color:#ad6c69;font-size:14px;word-break:break-all;">View inspiration link</a></div>`:"";
  return `<!doctype html><html><body style="margin:0;background:#f7f1ed;font-family:Arial,sans-serif;color:#2f2927;"><table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f7f1ed;padding:28px 12px;"><tr><td align="center"><table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:620px;background:#ffffff;border-radius:24px;overflow:hidden;box-shadow:0 8px 30px rgba(47,41,39,.08);"><tr><td style="padding:30px;background:#2f2927;text-align:center;"><p style="margin:0;color:#eed8d4;font-family:Georgia,serif;font-size:28px;">Nails <em>by</em> Ella</p><p style="margin:8px 0 0;color:#ffffff;font-size:11px;font-weight:700;letter-spacing:2px;text-transform:uppercase;">${isBooking?"New appointment inquiry":"New website message"}</p></td></tr><tr><td style="padding:30px;"><p style="margin:0;color:#ad6c69;font-size:12px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;">You received a message from</p><h1 style="margin:8px 0 22px;font-family:Georgia,serif;font-size:32px;font-weight:400;line-height:1.2;">${escapeHtml(name)}</h1><table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border:1px solid #eee5e1;border-radius:16px;border-collapse:separate;overflow:hidden;">${rows}</table>${inspirationBlock}<div style="margin-top:20px;padding:18px;background:#fbf7f5;border-radius:16px;"><p style="margin:0 0 8px;color:#8a7770;font-size:12px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;">Message</p><p style="margin:0;color:#2f2927;font-size:15px;line-height:1.7;white-space:pre-wrap;">${escapeHtml(note)}</p></div><div style="margin-top:24px;text-align:center;"><a href="mailto:${encodeURIComponent(email)}" style="display:inline-block;background:#2f2927;color:#ffffff;text-decoration:none;padding:14px 25px;border-radius:999px;font-size:14px;font-weight:700;">Reply to ${escapeHtml(name)}</a></div></td></tr><tr><td style="padding:18px 30px;background:#fbf7f5;text-align:center;color:#9b8982;font-size:11px;line-height:1.6;">Sent securely from the Nails by Ella website<br>By appointment only</td></tr></table></td></tr></table></body></html>`;
}

function plainText(notice: Notice) { return Object.entries(notice.payload).map(([key,item])=>`${key}: ${String(item)}`).join("\n"); }
function formatDate(date:string){const parts=date.split("-");if(parts.length!==3)return date;return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(`${date}T00:00:00Z`));}
function formatTime(time:string){const match=/^(\d{2}):(\d{2})$/.exec(time);if(!match)return time;const hour=Number(match[1]);return `${hour%12||12}:${match[2]} ${hour>=12?"PM":"AM"}`;}

function escapeHtml(value: string) {
  return value.replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#039;" }[c]!));
}
