import type { Context } from "@wrnexus/core";

function safeReturnPath(value: string | null, baseUrl: URL): string {
  if (!value) return "/protected";

  try {
    const destination = new URL(value, baseUrl);
    if (destination.origin !== baseUrl.origin) return "/protected";
    if (!destination.pathname.startsWith("/") || destination.pathname.startsWith("//")) {
      return "/protected";
    }
    return `${destination.pathname}${destination.search}`;
  } catch {
    return "/protected";
  }
}

export async function POST(ctx: Context): Promise<Response> {
  const contentType = ctx.req.headers.get("content-type") ?? "";
  let submittedReturnTo: string | null;

  if (contentType.includes("application/json")) {
    const body = (await ctx.req.json().catch(() => ({}))) as Record<string, unknown>;
    submittedReturnTo = typeof body.returnTo === "string" ? body.returnTo : null;
  } else {
    const form = await ctx.req.formData();
    const value = form.get("returnTo");
    submittedReturnTo = typeof value === "string" ? value : null;
  }

  const returnTo = submittedReturnTo ?? ctx.url.searchParams.get("returnTo");
  const safePath = safeReturnPath(returnTo, ctx.url);
  return Response.redirect(new URL(safePath, ctx.url), 303);
}
