import { q as query } from '../../../../chunks/db_Du3AmLCY.mjs';
export { renderers } from '../../../../renderers.mjs';

const POST = async ({ request }) => {
  try {
    const { html, subject, segment, product_id } = await request.json();
    const RESEND_KEY = process.env.RESEND_API_KEY || undefined                              ;
    if (!RESEND_KEY) return Response.json({ error: "RESEND_API_KEY not configured" }, { status: 500 });
    let recipients = [];
    if (segment === "watchlist-all") {
      const r = await query(`SELECT DISTINCT u.id as user_id, u.email FROM users u JOIN watchlist w ON w.user_id = u.id WHERE u.email_verified = true`);
      recipients = r.rows;
    } else if (segment === "watchlist-product" && product_id) {
      const r = await query(`SELECT DISTINCT u.id as user_id, u.email FROM users u JOIN watchlist w ON w.user_id = u.id WHERE w.product_id = $1 AND u.email_verified = true`, [product_id]);
      recipients = r.rows;
    } else {
      return Response.json({ error: "Invalid segment" }, { status: 400 });
    }
    let sent = 0, failed = 0;
    for (const r of recipients) {
      try {
        const res = await fetch("https://api.resend.com/emails", {
          method: "POST",
          headers: { "Authorization": `Bearer ${RESEND_KEY}`, "Content-Type": "application/json" },
          body: JSON.stringify({
            from: "SneakerPicks <noreply@sneakerpicks.nl>",
            to: r.email,
            subject: subject || "SneakerPicks Update",
            html
          })
        });
        if (res.ok) {
          const data = await res.json();
          await query(`INSERT INTO email_log (user_id, email_type, resend_id) VALUES ($1, 'bulk', $2)`, [r.user_id, data.id]);
          sent++;
        } else {
          failed++;
        }
      } catch {
        failed++;
      }
    }
    return Response.json({ ok: true, sent, failed, total: recipients.length });
  } catch (err) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  POST
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
