import { serve } from "https://deno.land/std@0.192.0/http/server.ts"; serve(async (req) => { // ✅ CORS preflight if (req.method === "OPTIONS") { return new Response("ok", { headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "*", }, }); } try { const { article, subscribers } = await req.json(); if (!article || !article.title) { return new Response(JSON.stringify({ error: "Article data is required" }), { status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, }); } if (!subscribers || subscribers.length === 0) { return new Response(JSON.stringify({ error: "No subscribers provided" }), { status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, }); } const RESEND_API_KEY = Deno.env.get("RESEND_API_KEY"); if (!RESEND_API_KEY) { throw new Error("RESEND_API_KEY is not set"); } const siteUrl = "https://broadcastbeat.com"; const articleUrl = article.slug ? `${siteUrl}/articles/${article.slug}` : article.wp_slug ? `${siteUrl}/articles/${article.wp_slug}` : siteUrl; const categoryLabel = article.category ? `${article.category}` : ""; const featuredImageBlock = article.featured_image ? `${article.featured_image_alt || article.title}` : ""; const excerptBlock = article.excerpt ? `

${article.excerpt}

` : ""; const authorBlock = article.author_name ? `

By ${article.author_name}

` : ""; const htmlBody = ` ${article.title} — BroadcastBeat
${featuredImageBlock ? `` : ""}

BroadcastBeat

Digital Platform for Broadcast Engineering

${featuredImageBlock}

New Article

${categoryLabel}

${article.title}

${authorBlock} ${excerptBlock} Read Article →

You're receiving this because you subscribed to BroadcastBeat article notifications.
Visit BroadcastBeat

`; const results = { sent: 0, failed: 0, errors: [] as string[] }; // Send in batches of 50 to respect Resend rate limits const batchSize = 50; for (let i = 0; i < subscribers.length; i += batchSize) { const batch = subscribers.slice(i, i + batchSize); const response = await fetch("https://api.resend.com/emails", { method: "POST", headers: { "Authorization": `Bearer ${RESEND_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ from: "onboarding@resend.dev", to: batch, subject: `New Article: ${article.title}`, html: htmlBody, }), }); const data = await response.json(); if (!response.ok) { results.failed += batch.length; results.errors.push(data.message || "Batch send failed"); } else { results.sent += batch.length; } } return new Response( JSON.stringify({ success: true, sent: results.sent, failed: results.failed, errors: results.errors }), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, } ); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, }); } });