import { authTicketLogin } from "@/auth/auth";
import * as ldap from "@/ldap";
import { loginSchema } from "@/schemas";

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

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

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

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