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

export const CUSTOMER_INVOICES_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 InvoicesQueryOptions = {
  enabled?: boolean;
  criteria?: CriteriaDTO
};

// Obtener todas las facturas
export const useInvoicesQuery = (options?: InvoicesQueryOptions) => {
  const dataSource = useDataSource();
  const enabled = options?.enabled ?? true;
  const criteria = options?.criteria ?? {};

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