import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { PaginationController } from "../../../useAppPagination";
import { apiGet } from "../../../../lib/api/methods";
import { ADMIN_PACKAGES } from "./endpoints";

export type Package = {
  uuid: string;
  name: string;
  description: string;
  credits: number;
  price: number;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
};

type AdminPackagesResponse = Array<Package>;

export default function useFetchPackages(pagination: PaginationController) {
  const { data, isPending, isError, error } = useQuery({
    queryKey: [
      "admin-packages",
      pagination.params.page,
      pagination.params.limit,
      pagination.params.searchQuery,
    ],
    queryFn: async () => {
      const res = await apiGet<AdminPackagesResponse>(
        ADMIN_PACKAGES.GET_PACKAGES,
        {
          limit: pagination.params.limit,
          page: pagination.params.page,
          search: pagination.params.searchQuery,
        },
      );

      return {
        packages: res.data,
        pagination: res.meta,
      };
    },
    staleTime: 60 * 1000,
    placeholderData: keepPreviousData,
  });

  return {
    data,
    loading: isPending,
    error,
    isError,
  };
}
