"use server";

import * as ldap from "@/ldap";
import { LoginSchema, loginSchema } from "@/schemas";
import { ActionResponse } from ".";
import { getLogger } from "@/logger";
import { authTicketLogin } from "@/auth/auth";

type Response = ActionResponse & {
  ticket?: string;
};

export default async function login(data: LoginSchema): Promise<Response> {
  const { username, password } = await loginSchema.parse(data);

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

  const [_, ticket] = await authTicketLogin(username);
  return { ok: true, ticket: ticket.ticket };
}
