/**
 * New-lead email notification.
 *
 * Provider-agnostic: the first configured provider wins. Configure exactly one
 * of the following sets of secrets and notifications start flowing immediately —
 * no code change required.
 *
 *   RESEND_API_KEY   (+ optional LEAD_FROM_EMAIL, defaults to onboarding@resend.dev)
 *   SENDGRID_API_KEY (+ LEAD_FROM_EMAIL, must be a verified sender)
 *
 * Recipient defaults to gazmanadvancedtechnologies@gmail.com and can be
 * overridden with LEAD_NOTIFICATION_EMAIL.
 */

export const LEAD_INBOX = "gazmanadvancedtechnologies@gmail.com";

export interface Lead {
  name: string;
  email: string;
  company?: string;
  message: string;
  source?: string;
}

function renderLead(lead: Lead) {
  const subject = `New enquiry from ${lead.name}${lead.company ? ` (${lead.company})` : ""}`;
  const text = [
    `Name: ${lead.name}`,
    `Email: ${lead.email}`,
    `Organization: ${lead.company || "—"}`,
    `Source: ${lead.source || "website"}`,
    "",
    lead.message,
  ].join("\n");
  const html = `<div style="font-family:Arial,sans-serif;line-height:1.6">
    <h2 style="margin:0 0 12px">New enquiry — Gatavase Corporation</h2>
    <p><strong>Name:</strong> ${escapeHtml(lead.name)}<br/>
    <strong>Email:</strong> ${escapeHtml(lead.email)}<br/>
    <strong>Organization:</strong> ${escapeHtml(lead.company || "—")}<br/>
    <strong>Source:</strong> ${escapeHtml(lead.source || "website")}</p>
    <p style="white-space:pre-wrap">${escapeHtml(lead.message)}</p>
  </div>`;
  return { subject, text, html };
}

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

export async function notifyNewLead(lead: Lead) {
  const to = process.env.LEAD_NOTIFICATION_EMAIL || LEAD_INBOX;
  // The submitter also receives the message at the address they provided.
  const recipients = Array.from(new Set([to, lead.email].filter(Boolean)));
  const from = process.env.LEAD_FROM_EMAIL || "Gatavase Website <onboarding@resend.dev>";
  const { subject, text, html } = renderLead(lead);

  const resendKey = process.env.RESEND_API_KEY;
  if (resendKey) {
    const res = await fetch("https://api.resend.com/emails", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        authorization: `Bearer ${resendKey}`,
      },
      body: JSON.stringify({ from, to: recipients, reply_to: lead.email, subject, html }),
    });
    if (!res.ok) {
      throw new Error(`Resend send failed [${res.status}]: ${await res.text()}`);
    }
    return { sent: true as const, provider: "resend" as const };
  }

  const sendgridKey = process.env.SENDGRID_API_KEY;
  if (sendgridKey) {
    const res = await fetch("https://api.sendgrid.com/v3/mail/send", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        authorization: `Bearer ${sendgridKey}`,
      },
      body: JSON.stringify({
        personalizations: [{ to: recipients.map((email) => ({ email })) }],
        from: { email: from.replace(/.*<|>.*/g, "") || to, name: "Gatavase Website" },
        reply_to: { email: lead.email },
        subject,
        content: [{ type: "text/html", value: html }],
      }),
    });
    if (!res.ok) {
      throw new Error(`SendGrid send failed [${res.status}]: ${await res.text()}`);
    }
    return { sent: true as const, provider: "sendgrid" as const };
  }

  // No provider configured yet — the lead is already stored in the dashboard.
  console.log(`[new-lead] (no email provider configured) -> ${to}\n${subject}\n${text}`);
  return { sent: false as const, provider: null };
}
