import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { AUTH_COOKIE_NAME, buildAuthCookieOptions } from "@/lib/auth";

const mercuryBase = `${process.env.MERCURY_INTERNAL_URL ?? "http://mercury-api:8000"}/api/v1`;

export async function POST(request: Request) {
  const body = await request.json();
  try {
    const response = await fetch(`${mercuryBase}/auth/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    });
    const data = await response.json();
    if (!response.ok) {
      return NextResponse.json(data, { status: response.status });
    }
    const cookieStore = await cookies();
    cookieStore.set({
      name: AUTH_COOKIE_NAME,
      value: data.access_token,
      ...buildAuthCookieOptions(data.expires_in)
    });
    return NextResponse.json({ user: data.user, expires_in: data.expires_in });
  } catch (error) {
    return NextResponse.json(
      { detail: "Der Anmeldedienst ist momentan nicht erreichbar." },
      { status: 502 }
    );
  }
}
