import { useOne, useSave } from "@/lib/hooks/useDataSource";
import { TDataSourceError } from "@/lib/hooks/useDataSource/types";
import { useDataSource } from "@/lib/hooks/useDataSource/useDataSource";
import { useQueryKey } from "@/lib/hooks/useQueryKey";
import {
  ICreateQuote_Request_DTO,
  ICreateQuote_Response_DTO,
  IGetQuote_Response_DTO,
  UniqueID,
} from "@shared/contexts";

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

export const useQuotes = (params?: UseQuotesGetParamsType) => {
  const dataSource = useDataSource();
  const keys = useQueryKey();

  return {
    useQuery: useOne<IGetQuote_Response_DTO>({
      queryKey: keys().data().resource("quotes").action("one").id("").params().get(),
      queryFn: () =>
        dataSource.getOne({
          resource: "quotes",
          id: "",
        }),
      ...params,
    }),
    useMutation: useSave<ICreateQuote_Response_DTO, TDataSourceError, ICreateQuote_Request_DTO>({
      mutationKey: keys().data().resource("quotes").action("one").id("").params().get(),
      mutationFn: (data) => {
        let { id } = data;

        if (!id) {
          id = UniqueID.generateNewID().object.toString();
        }

        return dataSource.updateOne({
          resource: "quotes",
          data,
          id,
        });
      },
    }),
  };
};
