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; nextPath?: unknown; fullName?: unknown }>(req);

  if (!body || typeof body.email !== "string") {
    return NextResponse.json({ error: "Keine E-Mail angegeben" }, { status: 400 });
  }

  const nextPath = typeof body.nextPath === "string" && body.nextPath.startsWith("/")
    ? body.nextPath
    : "/";
  const callbackUrl = new URL("/auth/callback", new URL(req.url).origin);
  callbackUrl.searchParams.set("next", nextPath);

  try {
    const supabase = await createRouteClient();
    const { error } = await supabase.auth.signInWithOtp({
      email: body.email.trim(),
      options: {
        emailRedirectTo: callbackUrl.toString(),
        data: typeof body.fullName === "string" ? { full_name: body.fullName.trim() } : undefined,
      },
    });

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

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