import { CriteriaDTO } from '@erp/core';
import { useDataSource } from "@erp/core/hooks";
import { DefaultError, QueryKey, useQuery } from "@tanstack/react-query";
import { CustomersPage } from '../schemas';


export const CUSTOMERS_QUERY_KEY = (criteria: CriteriaDTO): QueryKey => [
  "customer_invoices", {
    pageNumber: criteria.pageNumber ?? 0,
    pageSize: criteria.pageSize ?? 10,
    q: criteria.q ?? "",
    filters: criteria.filters ?? [],
    orderBy: criteria.orderBy ?? "",
    order: criteria.order ?? "",
  },
];

type CustomersQueryOptions = {
  enabled?: boolean;
  criteria?: CriteriaDTO
};

// Obtener todos los clientes
export const useCustomersQuery = (options?: CustomersQueryOptions) => {
  const dataSource = useDataSource();
  const enabled = options?.enabled ?? true;
  const criteria = options?.criteria ?? {};

  return useQuery<CustomersPage, DefaultError>({
    queryKey: CUSTOMERS_QUERY_KEY(criteria),
    queryFn: async ({ signal }) => {
      return await dataSource.getList<CustomersPage>("customers", {
        signal,
        ...criteria,
      });
    },
    enabled,
    placeholderData: (previousData, previousQuery) => previousData, // Mantener datos previos mientras se carga nueva datos (antiguo `keepPreviousData`)
  });
};
