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

function ChangeUsername(props: { nameChange: StrNameChange }): void {
  if (
    props.nameChange.newName === "" ||
    props.nameChange.newName === props.nameChange.prevName
  ) {
    alert("You have to give a new name\n\nName not changed");
    return;
  }
  if (props.nameChange.prevName === localStorage.getItem("username")) {
    alert("You cannot change admin name");
    return;
  }
  api
    .changeUserName(props.nameChange, localStorage.getItem("accessToken") ?? "")
    .then((response: APIResponse<void>) => {
      if (response.success) {
        alert("Name changed successfully");
        location.reload();
      } else {
        alert("Name not changed, name could be taken");
        console.error(response.message);
      }
    })
    .catch((error) => {
      alert("Name not changed");
      console.error("An error occurred during change:", error);
    });
}

export default ChangeUsername;
