import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/Service";
import {
  TemplateType,
  TemplatesResponseType,
  GetTemplateResponse,
} from "../types/Types";

export const useSaveTemplate = () => {
  return useMutation({
    mutationFn: (params: TemplateType) => api.saveTemplate(params),
  });
};

export const useGetTemplates = () => {
  return useQuery<TemplatesResponseType>({
    queryKey: ["templates"],
    queryFn: api.getTemplates,
  });
};

export const useSetSelectedTemplate = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.setSelectedTemplate(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
    },
  });
};

export const useGetTemplate = (id: string) => {
  return useQuery<GetTemplateResponse>({
    queryKey: ["template", id],
    queryFn: () => api.getTemplate(id),
    enabled: !!id,
  });
};

export const useUpdateTemplate = () => {
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: TemplateType }) =>
      api.updateTemplate({ id, params }),
  });
};

export const useDeleteTemplate = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.deleteTemplate(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
    },
  });
};

export const useSingleUpload = () => {
  return useMutation({
    mutationFn: (file: File) => api.singleUpload(file),
  });
};
