import { NextResponse } from "next/server";
import { getSessionCustomer, getCustomerProfile, getCustomerOrders, getCustomerOrderDetail } from "../../../lib/customerAuth";

// GDPR data portability (Art. 20) — a full, structured, machine-readable
// export of everything tied to the account: profile + every order's full
// detail (not just the summary list, so this is a genuinely complete
// export, not a teaser).
export async function GET() {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const profile = await getCustomerProfile(session.token);
  const orderSummaries = await getCustomerOrders(session.token, session.customer.id, false);
  const orders = await Promise.all(
    orderSummaries.map((o) => getCustomerOrderDetail(session.token, session.customer.id, o.orderNumber, false)),
  );

  const payload = {
    exportedAt: new Date().toISOString(),
    profile,
    orders: orders.filter(Boolean),
  };

  return new NextResponse(JSON.stringify(payload, null, 2), {
    headers: {
      "Content-Type": "application/json",
      "Content-Disposition": 'attachment; filename="meine-daten.json"',
    },
  });
}
