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,
  IUpdateQuote_Request_DTO,
  IUpdateQuote_Response_DTO,
  UniqueID,
} from "@shared/contexts";

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

export const useQuotes = () => {
  const dataSource = useDataSource();
  const keys = useQueryKey();

  return {
    useOne: (id?: string, params?: UseQuotesGetParamsType) =>
      useOne<IGetQuote_Response_DTO>({
        queryKey: keys().data().resource("quotes").action("one").id("").params().get(),
        queryFn: () =>
          dataSource.getOne({
            resource: "quotes",
            id: String(id),
          }),
        enabled: !!id,
        ...params,
      }),
    useCreate: () =>
      useSave<ICreateQuote_Response_DTO, TDataSourceError, ICreateQuote_Request_DTO>({
        mutationKey: keys().data().resource("quotes").action("one").id("").params().get(),
        mutationFn: (data) => {
          let { id, status } = data;

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

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

    useUpdate: (id: string) =>
      useSave<IUpdateQuote_Response_DTO, TDataSourceError, IUpdateQuote_Request_DTO>({
        mutationKey: keys().data().resource("quotes").action("one").id(id).params().get(),
        mutationFn: (data) => {
          return dataSource.updateOne({
            resource: "quotes",
            id,
            data,
          });
        },
      }),
  };
};
