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

export const CUSTOMER_DETAIL_SCOPE = "customers:detail" as const;

export const getCustomerQueryKey = (id: string) =>
  [CUSTOMER_DETAIL_SCOPE, { id }] satisfies QueryKey;

type CustomerQueryOptions<TSelected> = {
  enabled?: boolean;
  staleTime?: number;
  select?: (data: Customer) => TSelected;
  placeholderData?: Customer;
};

export function useCustomerQuery<TSelected = Customer>(
  customerId?: string,
  options?: CustomerQueryOptions<TSelected>
) {
  const dataSource = useDataSource();
  const enabled = (options?.enabled ?? true) && Boolean(customerId);

  return useQuery<Customer, DefaultError, TSelected>({
    queryKey: getCustomerQueryKey(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,
    staleTime: options?.staleTime ?? 60_000, // 1 min por defecto
    select: options?.select,
    placeholderData: options?.placeholderData,
  });
}

export function invalidateCustomerDetailCache(qc: QueryClient, id: string) {
  return qc.invalidateQueries({
    queryKey: getCustomerQueryKey(id ?? "unknown"),
    exact: Boolean(id),
  });
}

export function setCustomerDetailCache(qc: QueryClient, id: string, data: unknown) {
  qc.setQueryData(getCustomerQueryKey(id), data);
}
