import { TOKEN_NAME } from "@/configs";
import { getFetchInstance } from "@/configs/getFetchInstance";
import Cookies from "js-cookie";
import { getNestedProperty } from "./helper";

export const getToken = () => {
  const token = Cookies.get(TOKEN_NAME);

  return token;
};

export const staticPaginationPageGenerator = async ({
  url,
  paramKey,
  exceptKey,
  config,
}: {
  url: string;
  paramKey: string;
  exceptKey: string;
  config?: any;
}) => {
  try {
    const response: any = await getFetchInstance({
      url: `${url}?per_page=100`,
      config,
    });
    const data = response?.data?.data || [];
    const totalPages = response?.data?.last_page || 1;

    if (totalPages > 1) {
      const pageRequests = Array.from({ length: totalPages - 1 }, (_, i) =>
        getFetchInstance({ url: `${url}?per_page=100&page=${i + 2}`, config }),
      );

      const responses = await Promise.all(pageRequests);

      responses.forEach((res: any) => {
        if (res?.data?.data) {
          data.push(...res.data.data);
        }
      });
    }

    if (!data.length) return [{ [paramKey]: "not-found" }];

    return data.map((object: any) => ({
      [paramKey]: getNestedProperty(object, exceptKey),
    }));
  } catch (error) {
    console.warn("Error fetching quizzes:", error);
    return [{ [paramKey]: "not-found" }];
  }
};
