import { NextResponse } from "next/server";
import { upsertNewsletterContact, type NewsletterOptInSource } from "../../../lib/brevo";
import { isValidEmail } from "../../../lib/email";

type SubscribeBody = {
  email?: string;
  consent?: boolean;
  source?: NewsletterOptInSource;
};

const VALID_SOURCES: NewsletterOptInSource[] = ["newsletter-page", "newsletter-modal", "newsletter-hero", "challenge"];

export async function POST(req: Request) {
  const body: SubscribeBody = await req.json();
  const email = body.email?.trim() ?? "";

  if (!isValidEmail(email)) {
    return NextResponse.json({ ok: false, reason: "Bitte gib eine gültige E-Mail-Adresse ein." }, { status: 400 });
  }
  if (!body.consent) {
    return NextResponse.json({ ok: false, reason: "Bitte akzeptiere die Datenschutzerklärung." }, { status: 400 });
  }

  const source = body.source && VALID_SOURCES.includes(body.source) ? body.source : "newsletter-page";
  const result = await upsertNewsletterContact(email, source);
  if (!result.ok) {
    // The customer-facing message stays generic on purpose (never leak
    // Brevo's internal error text to a customer) — but the real reason
    // was previously discarded entirely, which cost real debugging time
    // tracking down a misconfigured BREVO_LIST_ID in Coolify (2026-07-25):
    // every failure looked identical from the outside, whether it was a
    // bad env var, a Brevo outage, or something else. Logged here so it's
    // at least diagnosable from the container's own logs going forward.
    console.error(`newsletter subscribe failed for source=${source}: ${result.reason}`);
    return NextResponse.json({ ok: false, reason: "Anmeldung ist fehlgeschlagen. Bitte versuche es später erneut." }, { status: 502 });
  }
  return NextResponse.json({ ok: true, alreadySubscribed: result.alreadySubscribed ?? false });
}
