import { sendSiteSmtpMail } from "@/lib/site-smtp-mail";

function escapeHtml(value: string) {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#039;");
}

export async function sendContactMessageEmail(data: {
  name: string;
  email: string;
  sector?: string | null;
  message: string;
}) {
  const sector = data.sector?.trim() || "—";
  const subject = `Contato site — ${data.name}`;
  const text = [
    "Nova mensagem pelo formulário de contato",
    `Nome: ${data.name}`,
    `E-mail: ${data.email}`,
    `Setor: ${sector}`,
    "",
    "Mensagem:",
    data.message,
  ].join("\n");

  const html = `
    <div style="font-family: Arial, Helvetica, sans-serif; color: #111;">
      <h2 style="margin: 0 0 12px 0;">Nova mensagem — Contato</h2>
      <p style="margin: 0 0 8px 0;"><b>Nome:</b> ${escapeHtml(data.name)}</p>
      <p style="margin: 0 0 8px 0;"><b>E-mail:</b> ${escapeHtml(data.email)}</p>
      <p style="margin: 0 0 8px 0;"><b>Setor:</b> ${escapeHtml(sector)}</p>
      <p style="margin: 12px 0 0 0;"><b>Mensagem:</b></p>
      <p style="margin: 8px 0 0 0; white-space: pre-wrap;">${escapeHtml(data.message)}</p>
      <hr style="border: none; border-top: 1px solid #eee; margin: 16px 0;" />
      <p style="margin: 0; color: #666; font-size: 12px;">Enviado pelo site fluminensedefeira.com.br</p>
    </div>
  `;

  await sendSiteSmtpMail({
    subject,
    text,
    html,
    replyTo: data.email,
    fromName: "Fluminense de Feira — Contato",
  });
}
