import { useOne } 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 {
  IGetProfileResponse_DTO,
  IUpdateProfile_Request_DTO,
  IUpdateProfileResponse_DTO,
} from "@shared/contexts";
import { useMutation, useQueryClient } from "@tanstack/react-query";

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

export const useSettings = (params?: UseSettingsGetParamsType) => {
  const dataSource = useDataSource();
  const keys = useQueryKey();

  return {
    useOne: () =>
      useOne<IGetProfileResponse_DTO>({
        queryKey: keys().data().resource("settings").action("one").id("me").params().get(),
        queryFn: () =>
          dataSource.getOne({
            resource: "profile",
            id: "",
          }),
        ...params,
      }),

    useUpdate: () => {
      const queryClient = useQueryClient();

      return useMutation<IUpdateProfileResponse_DTO, TDataSourceError, IUpdateProfile_Request_DTO>({
        mutationKey: keys().data().resource("settings").action("one").id("me").params().get(),
        mutationFn: (data) => {
          return dataSource.updateOne({
            resource: "profile",
            data,
            id: "",
          });
        },
        onSuccess: () => {
          queryClient.invalidateQueries({
            queryKey: ["data", "default", "settings"],
          });
        },
      });
    },
    useUploadLogo: () => {
      const queryClient = useQueryClient();

      const { mutate, mutateAsync, ...rest } = useMutation<
        any, //IUploadProfileLogoResponse_DTO,
        TDataSourceError,
        any
      >({
        mutationKey: ["data", "default", "settings"], //keys().data().resource("settings").action("upload").id("me").params().get(),
        mutationFn: (data) => {
          return dataSource.uploadFile({
            path: "profile/logo",
            //resource: "profile",
            //id: "",
            file: data,
            key: "logo",
          });
        },
        onError: () => {
          return queryClient.invalidateQueries({
            queryKey: ["data", "default", "settings"],
          });
        },
        onSuccess: () => {
          queryClient.invalidateQueries({
            queryKey: ["data", "default", "settings"],
          });
        },
      });
      return {
        upload: mutate,
        uploadAsync: mutateAsync,
        ...rest,
      };
    },
  };
};
