import { APIResponse, api } from "../API/API";
import { NewProjMember } from "../Types/goTypes";

/**
 * Tries to add a member to a project
 * @param {Object} props - A NewProjMember
 * @returns {boolean} True if added, false if not
 */
function AddMember(props: { memberToAdd: NewProjMember }): boolean {
  let added = false;
  if (
    props.memberToAdd.username === "" ||
    props.memberToAdd.role === "" ||
    props.memberToAdd.projectname === ""
  ) {
    alert("All fields must be filled before adding");
    return added;
  }
  api
    .addUserToProject(
      props.memberToAdd,
      localStorage.getItem("accessToken") ?? "",
    )
    .then((response: APIResponse<NewProjMember>) => {
      if (response.success) {
        alert("Member added");
        added = true;
      } else {
        alert("Member not added");
        console.error(response.message);
      }
    })
    .catch((error) => {
      console.error("An error occurred during member add:", error);
    });
  return added;
}

export default AddMember;
