import { NextResponse } from "next/server";

import { issueJwtToken } from "@/lib/jwt";
import { authenticateAuthUser } from "@/lib/auth";
import { loginSchema } from "@/validators/auth";

function getCookieSettings() {
  const isProduction = process.env.NODE_ENV === "production";

  return {
    httpOnly: true,
    sameSite: isProduction ? ("none" as const) : ("lax" as const),
    secure: isProduction,
    path: "/",
    maxAge: 24 * 60 * 60,
  };
}

export async function POST(request: Request) {
  let body: unknown;

  try {
    body = await request.json();
  } catch {
    return NextResponse.json(
      { message: "Invalid JSON payload" },
      { status: 400 },
    );
  }

  const parsedBody = loginSchema.safeParse(body);

  if (!parsedBody.success) {
    return NextResponse.json(
      {
        message: "Validation failed",
        errors: parsedBody.error.flatten(),
      },
      { status: 400 },
    );
  }

  try {
    const authUser = await authenticateAuthUser(
      parsedBody.data.username,
      parsedBody.data.password,
    );

    if (!authUser) {
      return NextResponse.json(
        { message: "Invalid credentials" },
        { status: 401 },
      );
    }

    const token = issueJwtToken(authUser.username, authUser.role);

    const response = NextResponse.json({
      message: "Login successful",
      token,
      tokenType: "Bearer",
      user: authUser,
    });

    response.cookies.set({
      name: "auth_token",
      value: token,
      ...getCookieSettings(),
    });

    // Ensure CORS credentials allowed when called from frontend origin
    const FRONTEND_ORIGIN = process.env.FRONTEND_ORIGIN ?? "http://localhost:3000";
    response.headers.set("Access-Control-Allow-Origin", FRONTEND_ORIGIN);
    response.headers.set("Access-Control-Allow-Credentials", "true");

    return response;
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Authentication unavailable";

    return NextResponse.json({ message }, { status: 500 });
  }
}
