import { NextRequest, NextResponse } from "next/server";
import { proxyRequest } from "@/lib/backend";
import { setAuthCookies } from "@/lib/auth-cookies";

export async function POST(req: NextRequest) {
  const res = await proxyRequest(req, "auth/register");
  const payload = await res.clone().json().catch(() => null) as { data?: { accessToken?: string; refreshToken?: string; sessionNonce?: string; [key: string]: unknown } } | null;
  if (res.ok && payload?.data?.accessToken && payload.data.refreshToken && payload.data.sessionNonce) {
    const { accessToken, refreshToken, sessionNonce, ...safeData } = payload.data;
    const safeRes = NextResponse.json({ ...payload, data: safeData }, { status: res.status });
    setAuthCookies(safeRes, accessToken, refreshToken, sessionNonce);
    return safeRes;
  }
  return res;
}
