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 }>(req);

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

  try {
    const supabase = await createRouteClient();
    const { error } = await supabase.auth.signInWithPassword({
      email: body.email.trim(),
      password: body.password,
    });

    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 },
    );
  }
}
