import * as ldap from "@/ldap";
import { createAuthTicket } from "@/auth";

type RequestBody = {
  username: string;
  password: string;
};

export async function POST(request: Request) {
  const { username, password } = (await request.json()) as RequestBody;

  if (
    username == undefined ||
    typeof username !== "string" ||
    password == undefined ||
    typeof password !== "string"
  ) {
    return new Response(
      JSON.stringify({
        ok: false,
        error: "invalidBody"
      }),
      { status: 400 }
    );
  }

  const valid = await ldap.validateUser(username, password);
  if (!valid) {
    return new Response(
      JSON.stringify({
        ok: false,
        error: "invalidCredentials"
      }),
      { status: 401 }
    );
  }

  const ticket = await createAuthTicket(username);
  // not confident if we can set-cookie and I cba to try
  return new Response(JSON.stringify({ ok: true, ticket }));
}
