import type { APIRoute } from 'astro';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { html, subject } = await request.json();
    const RESEND_KEY = process.env.RESEND_API_KEY || import.meta.env.RESEND_API_KEY;
    const ADMIN_EMAIL = process.env.ADMIN_EMAIL || import.meta.env.ADMIN_EMAIL || 'admin@sneakerpicks.nl';

    if (!RESEND_KEY) return Response.json({ error: 'RESEND_API_KEY not configured' }, { status: 500 });

    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: ADMIN_EMAIL,
        subject: subject || 'Test Email - SneakerPicks',
        html,
      }),
    });

    const data = await res.json();
    if (!res.ok) return Response.json({ error: data.message || 'Send failed' }, { status: 500 });
    return Response.json({ ok: true, id: data.id });
  } catch (err: any) {
    return Response.json({ error: err.message }, { status: 500 });
  }
};
