/**
 * Go-live email broadcast for the Live Podcast.
 * Provider-agnostic: RESEND_API_KEY or SENDGRID_API_KEY (see notify.server.ts).
 */

export async function sendGoLiveEmails(recipients: string[], title: string, url: string) {
  if (!recipients.length) return { sent: false as const, provider: null, count: 0 };

  const from = process.env.LEAD_FROM_EMAIL || "Gatavase Live <onboarding@resend.dev>";
  const subject = `We're live now: ${title}`;
  const html = `<div style="font-family:Arial,sans-serif;line-height:1.6">
    <h2 style="margin:0 0 12px">The Gatavase Live Podcast is on air</h2>
    <p><strong>${escapeHtml(title)}</strong> has just started.</p>
    <p><a href="${url}" style="background:#0ea5e9;color:#fff;padding:10px 18px;border-radius:8px;text-decoration:none">Watch the live stream</a></p>
    <p style="font-size:12px;color:#666">You are receiving this because you asked for Gatavase Live alerts.</p>
  </div>`;

  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, 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, count: recipients.length };
  }

  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: recipients.map((email) => ({ to: [{ email }] })),
        from: { email: from.replace(/.*<|>.*/g, "") || "info@gatavase.com", name: "Gatavase Live" },
        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, count: recipients.length };
  }

  console.log(`[go-live] (no email provider configured) ${subject} -> ${recipients.length} subscribers`);
  return { sent: false as const, provider: null, count: recipients.length };
}

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