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 { email, topics } = await req.json();
if (!email) {
return new Response(JSON.stringify({ error: "Email is required" }), {
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 topicsList = topics && topics.length > 0
? `
${topics.map((t: string) => `- ${t}
`).join("")}
`
: "All topics
";
const htmlBody = `
Welcome to BroadcastBeat
|
BroadcastBeat
Digital Platform for Broadcast Engineering
|
|
Newsletter Confirmed
You're subscribed!
Thanks for subscribing to BroadcastBeat. You'll receive the latest broadcast industry news, product launches, and insights delivered straight to your inbox.
Your selected topics:
${topicsList}
Read Latest News →
|
|
You're receiving this because you subscribed at BroadcastBeat.
No spam — unsubscribe anytime by replying to this email.
|
|
`;
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: [email],
subject: "You're subscribed to BroadcastBeat!",
html: htmlBody,
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Failed to send email");
}
return new Response(JSON.stringify({ success: true, id: data.id }), {
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": "*",
},
});
}
});