import type { APIRoute } from 'astro';
import { query } from '../../../../lib/db';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { html, subject, segment, product_id } = await request.json();
    const RESEND_KEY = process.env.RESEND_API_KEY || import.meta.env.RESEND_API_KEY;
    if (!RESEND_KEY) return Response.json({ error: 'RESEND_API_KEY not configured' }, { status: 500 });

    let recipients: { email: string; user_id: string }[] = [];

    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: any) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};
