import { sendSiteSmtpMail } from "@/lib/site-smtp-mail";
import { BASE_LABEL, type BaseCategoryValue } from "@/lib/base-category";

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

export async function sendBaseContactEmail(data: {
  category: BaseCategoryValue;
  name: string;
  email: string;
  phone?: string | null;
  message?: string | null;
}) {
  const categoryLabel = BASE_LABEL[data.category];
  const to = data.category === "TOURINHOS" ? "tourinhos@fluminensedefeira.com.br" : "torcedor@fluminensedefeira.com.br";
  const phone = data.phone?.trim() || "—";
  const message = data.message?.trim() || "";
  const subject = `Contato A Base — ${categoryLabel} — ${data.name}`;

  const text = [
    `Nova mensagem da categoria ${categoryLabel}`,
    `Nome: ${data.name}`,
    `E-mail: ${data.email}`,
    `Telefone: ${phone}`,
    message ? "Mensagem:" : null,
    message || null,
  ]
    .filter(Boolean)
    .join("\n");

  const html = `
    <div style="font-family: Arial, Helvetica, sans-serif; color: #111;">
      <h2 style="margin: 0 0 12px 0;">Contato A Base - ${escapeHtml(categoryLabel)}</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>Telefone:</b> ${escapeHtml(phone)}</p>
      ${
        message
          ? `<p style="margin: 12px 0 0 0;"><b>Mensagem:</b></p><p style="margin: 8px 0 0 0; white-space: pre-wrap;">${escapeHtml(
              message,
            )}</p>`
          : `<p style="margin: 12px 0 0 0; color: #555;">Mensagem não informada.</p>`
      }
    </div>
  `;

  await sendSiteSmtpMail({
    to,
    subject,
    text,
    html,
    replyTo: data.email,
    fromName: `Fluminense de Feira — ${categoryLabel}`,
  });
}

