import { NextResponse } from "next/server";
import { deleteCustomerAccount, getSessionCustomer, loginCustomer, clearSessionCookie } from "../../../lib/customerAuth";

// GDPR self-service deletion. Password re-verified here (not just trusting
// the active session) before anything is deleted — same reasoning as
// changeCustomerPassword. See customerAuth.ts's deleteCustomerAccount for
// what actually survives (past orders, anonymized-by-omission — their own
// snapshot fields aren't touched, only the account/login disappears).
export async function POST(request: Request) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const body = await request.json().catch(() => null);
  const password = typeof body?.password === "string" ? body.password : "";
  if (!password) return NextResponse.json({ ok: false, reason: "Bitte dein Passwort zur Bestätigung eingeben." }, { status: 400 });

  const verify = await loginCustomer({ email: session.customer.email, password });
  if (!verify.ok) return NextResponse.json({ ok: false, reason: "Passwort ist falsch." }, { status: 400 });

  const deleted = await deleteCustomerAccount(verify.token, session.customer.id);
  if (!deleted) return NextResponse.json({ ok: false, reason: "Konto konnte nicht gelöscht werden." }, { status: 500 });

  await clearSessionCookie();
  return NextResponse.json({ ok: true });
}
