import { NewUser } from "../Types/goTypes";
import { api, APIResponse } from "../API/API";
import { Dispatch, SetStateAction } from "react";

/*
 * Checks if user is in database with api.login and then sets proper authority level
 * TODO: change so that it checks for user type (admin, user, pm) somehow instead
 **/
function LoginCheck(props: {
  username: string;
  password: string;
  setAuthority: Dispatch<SetStateAction<number>>;
}): void {
  const user: NewUser = {
    username: props.username,
    password: props.password,
  };

  localStorage.clear();

  api
    .login(user)
    .then((response: APIResponse<string>) => {
      if (response.success) {
        if (response.data !== undefined) {
          const token = response.data;
          localStorage.setItem("accessToken", token);
          //TODO: change so that it checks for user type (admin, user, pm) instead
          if (token !== "" && props.username === "admin") {
            props.setAuthority((prevAuth) => {
              prevAuth = 1;
              return prevAuth;
            });
          } else if (token !== "" && props.username === "pm") {
            props.setAuthority((prevAuth) => {
              prevAuth = 2;
              return prevAuth;
            });
          } else if (token !== "" && props.username === "user") {
            props.setAuthority((prevAuth) => {
              prevAuth = 3;
              return prevAuth;
            });
          }
        } else {
          console.error("Token was undefined");
        }
      } else {
        console.error("Token could not be fetched/No such user");
      }
    })
    .catch((error) => {
      console.error("An error occurred during login:", error);
    });
}

export default LoginCheck;
