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

export const CUSTOMER_INVOICE_QUERY_KEY = (id: string): QueryKey =>
  ["customer_invoice", id] as const;

type InvoiceQueryOptions = {
  enabled?: boolean;
};

export const useInvoiceQuery = (invoiceId?: string, options?: InvoiceQueryOptions) => {
  const dataSource = useDataSource();
  const enabled = (options?.enabled ?? true) && !!invoiceId;

  return useQuery<CustomerInvoice, DefaultError>({
    queryKey: CUSTOMER_INVOICE_QUERY_KEY(invoiceId ?? "unknown"),
    queryFn: async (context) => {
      const { signal } = context;
      if (!invoiceId) {
        if (!invoiceId) throw new Error("invoiceId is required");
      }
      return await dataSource.getOne<CustomerInvoice>("customer-invoices", invoiceId, {
        signal,
      });
    },
    enabled,
  });
};

/*
    export function useQuery<
      TQueryFnData = unknown,
      TError = unknown,
      TData = TQueryFnData,
      TQueryKey extends QueryKey = QueryKey
    >

    TQueryFnData: the type returned from the queryFn.
    TError: the type of Errors to expect from the queryFn.
    TData: the type our data property will eventually have. 
           Only relevant if you use the select option,
           because then the data property can be different 
           from what the queryFn returns. 
           Otherwise, it will default to whatever the queryFn returns.
    TQueryKey: the type of our queryKey, only relevant 
            if you use the queryKey that is passed to your queryFn.

*/
