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

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

type CustomerQueryOptions = {
  enabled?: boolean;
};

export function useCustomerQuery(customerId?: string, options?: CustomerQueryOptions) {
  const dataSource = useDataSource();
  const enabled = (options?.enabled ?? true) && !!customerId;

  return useQuery<Customer, DefaultError>({
    queryKey: CUSTOMER_QUERY_KEY(customerId ?? "unknown"),
    queryFn: async (context) => {
      const { signal } = context;
      if (!customerId) {
        if (!customerId) throw new Error("customerId is required");
      }
      return await dataSource.getOne<Customer>("customers", customerId, {
        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.

*/
