import { NextResponse } from 'next/server';

export const runtime = 'edge';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

/**
 * Forwards a subscribe request to Buttondown (https://buttondown.email).
 * Buttondown was picked because it's a one-key, one-endpoint API well suited
 * to a solo writer's newsletter — swap this for ConvertKit/Mailchimp/etc. if
 * you use something else, the shape of this route stays the same.
 *
 * Set BUTTONDOWN_API_KEY in your deployment's environment variables
 * (Netlify: Site settings → Environment variables) to activate it.
 */
export async function POST(req: Request) {
  let email: string | undefined;

  try {
    const body = await req.json();
    email = body?.email;
  } catch {
    return NextResponse.json({ ok: false, error: 'invalid_body' }, { status: 400 });
  }

  if (!email || !EMAIL_RE.test(email)) {
    return NextResponse.json({ ok: false, error: 'invalid_email' }, { status: 400 });
  }

  const apiKey = process.env.BUTTONDOWN_API_KEY;

  if (!apiKey) {
    // Not wired up yet. Tell the developer in the server logs; don't show a
    // fake success to the visitor, since the email genuinely didn't go
    // anywhere.
    console.warn(
      '[subscribe] BUTTONDOWN_API_KEY is not set — no newsletter provider is connected yet.'
    );
    return NextResponse.json(
      { ok: false, error: 'not_configured' },
      { status: 503 }
    );
  }

  try {
    const res = await fetch('https://api.buttondown.email/v1/subscribers', {
      method: 'POST',
      headers: {
        Authorization: `Token ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email }),
    });

    // Buttondown returns 400 if the address is already subscribed —
    // treat that as success from the visitor's point of view.
    if (res.ok || res.status === 400) {
      return NextResponse.json({ ok: true });
    }

    return NextResponse.json({ ok: false, error: 'provider_error' }, { status: 502 });
  } catch {
    return NextResponse.json({ ok: false, error: 'network' }, { status: 502 });
  }
}
