import { NextResponse } from "next/server";
import { authErrorMessage } from "@/lib/api/auth-errors";
import { readJsonBody } from "@/lib/api/security";
import { createRouteClient } from "@/lib/supabase/route";

export async function POST(req: Request) {
  const body = await readJsonBody<{
    email?: unknown;
    password?: unknown;
    fullName?: unknown;
  }>(req);

  if (
    !body ||
    typeof body.email !== "string" ||
    typeof body.password !== "string" ||
    typeof body.fullName !== "string"
  ) {
    return NextResponse.json({ error: "Ungültige Registrierungsdaten" }, { status: 400 });
  }

  const callbackUrl = new URL("/auth/callback", new URL(req.url).origin);
  callbackUrl.searchParams.set("next", "/");

  try {
    const supabase = await createRouteClient();
    const { data, error } = await supabase.auth.signUp({
      email: body.email.trim(),
      password: body.password,
      options: {
        data: {
          full_name: body.fullName.trim(),
        },
        emailRedirectTo: callbackUrl.toString(),
      },
    });

    if (error) {
      const authError = authErrorMessage(error);
      return NextResponse.json({ error: authError.message }, { status: authError.status });
    }

    return NextResponse.json({ ok: true, hasSession: !!data.session });
  } catch {
    return NextResponse.json(
      { error: "Der Auth-Dienst ist gerade nicht erreichbar. Prüfe Internet/DNS und die Supabase-Projekt-URL." },
      { status: 503 },
    );
  }
}
