import { Dispatch, useEffect } from "react";
import { Project } from "../Types/goTypes";
import { api } from "../API/API";

/**
 * Gets all projects that user is a member of
 * @param {Dispatch} props.setProjectsProp - A setStateAction for the array you want to put projects in
 * @param {string} props.username - Username
 * @returns {void} Nothing
 * @example
 *  const username = "Example";
 *  const [projects, setProjects] = useState<Project[]>([]);
 *  GetProjects({ setProjectsProp: setProjects, username: username });
 */
function GetProjects(props: {
  setProjectsProp: Dispatch<React.SetStateAction<Project[]>>;
  username: string;
}): void {
  const setProjects: Dispatch<React.SetStateAction<Project[]>> =
    props.setProjectsProp;
  useEffect(() => {
    const fetchUsers = async (): Promise<void> => {
      try {
        const token = localStorage.getItem("accessToken") ?? "";
        const response = await api.getUserProjects(props.username, token);
        if (response.success) {
          setProjects(response.data ?? []);
        } else {
          console.error("Failed to fetch projects:", response.message);
        }
      } catch (error) {
        console.error("Error fetching projects:", error);
      }
    };

    void fetchUsers();
  }, [props.username, setProjects]);
}

export default GetProjects;
