import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { DASHBOARD_ENDPOINTS } from "./endpoints";
import { apiGet } from "../../../lib/api/methods";
import { PaginationController } from "../../useAppPagination";
import { TransactionStatus } from "../../../components/table/features/transactions/types/transaction";

export type TransactionHistoryRecord = {
  uuid: string;
  userUuid: string;
  userName: string;
  email: string;
  packageName: string;
  amount: string;
  currency: string;
  provider: "stripe";
  credits: string;
  gatewayTransactionId: string;
  gatewayPaymentId: string;
  failureReason: string;
  status: TransactionStatus;
  createdAt: string;
};

type TransactionHistoryResponse = {
  user: {
    uuid: string;
    name: string;
    email: string;
    createdAt: string;
  };
  transactions: Array<TransactionHistoryRecord>;
};

export default function useTransacationHistoryFetch(
  pagination: PaginationController,
) {
  const { data, isPending, isError, error } = useQuery({
    queryKey: [
      "dashboard-transactions",
      pagination.params.page,
      pagination.params.limit,
      pagination.params.searchQuery,
      pagination.params.sortBy,
      pagination.params.sortDirection,
    ],
    queryFn: async () => {
      const queryParams = {
        limit: pagination.params.limit,
        page: pagination.params.page,
        search: pagination.params.searchQuery,
        sortBy: pagination.params.sortBy,
        sortOrder: pagination?.params?.sortDirection?.toUpperCase(),
      };
      const response = await apiGet<TransactionHistoryResponse>(
        DASHBOARD_ENDPOINTS.GET_TRANSACTION_HISTORY,
        queryParams,
      );

      return {
        transactions: response.data.transactions,
        pagination: response.meta,
      };
    },
    staleTime: 2 * 60 * 1000,
    placeholderData: keepPreviousData,
  });

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