import { IListResponseDTO } from "@erp/core";
import {
  IGetListDataProviderParams,
  UseListQueryResult,
  useDataSource,
  useList,
  useQueryKey,
} from "@erp/core/hooks";
import { IListInvoicesResponseDTO } from "@erp/invoices/common/dto";

export type UseInvoicesListParams = Omit<IGetListDataProviderParams, "filters" | "resource"> & {
  status?: string;
  enabled?: boolean;
  queryOptions?: Record<string, unknown>;
};

export type UseInvoicesListResponse = UseListQueryResult<
  IListResponseDTO<IListInvoicesResponseDTO>,
  unknown
>;

export type UseInvoicesGetParamsType = {
  enabled?: boolean;
  queryOptions?: Record<string, unknown>;
};

export type UseInvoicesReportParamsType = {
  enabled?: boolean;
  queryOptions?: Record<string, unknown>;
};

export const useInvoices = () => {
  const actions = {
    /**
     * Hook para obtener la lista de facturas
     * @param params - Parámetros para la consulta de la lista de facturas
     * @returns - Respuesta de la consulta de la lista de facturas
     */
    useList: (params: UseInvoicesListParams): UseInvoicesListResponse => {
      const dataSource = useDataSource();
      const keys = useQueryKey();

      const {
        pagination,
        status = "draft",
        quickSearchTerm = undefined,
        enabled = true,
        queryOptions,
      } = params;

      return useList({
        queryKey: keys().data().resource("invoices").action("list").params(params).get(),
        queryFn: () => {
          return dataSource.getList({
            resource: "invoices",
            quickSearchTerm,
            filters:
              status !== "all"
                ? [
                    {
                      field: "status",
                      operator: "eq",
                      value: status,
                    },
                  ]
                : [
                    {
                      field: "status",
                      operator: "ne",
                      value: "archived",
                    },
                  ],
            pagination,
          });
        },
        enabled,
        queryOptions,
      });
    },
  };
  return actions;
};
