import { useMutation, useQuery } from "@tanstack/react-query";
import {
  adoptDelegationTemplate,
  createDelegationTemplate,
  deleteDelegationTemplate,
  getDelegationTemplateById,
  getDelegationTemplates,
  updateDelegationTemplate,
} from "@/super-admin/services/api/delegationTemplate";
import { CreateTemplateTypes } from "../types/templateTypes";
import { AdoptTemplateTypes } from "../template";

export const useTemplate = (id?: string) => {
  const {
    data: templates,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["templates"],
    queryFn: async () => {
      return await getDelegationTemplates();
    },
  });

  const {
    data: template,
    isLoading: isLoadingTemplate,
    isError: isErrorTemplate,
    refetch: refetchTemplate,
  } = useQuery({
    queryKey: ["template", id],
    queryFn: async () => {
      return await getDelegationTemplateById(id!, { take: 300 });
    },
  });

  const {
    mutate: createTemplate,
    isPending: isCreatingTemplate,
    isError: isErrorCreateTemplate,
  } = useMutation({
    mutationFn: async (template: CreateTemplateTypes) => {
      return await createDelegationTemplate(template);
    },
  });

  const {
    mutate: updateTemplate,
    isPending: isUpdatingTemplate,
    isError: isErrorUpdateTemplate,
  } = useMutation({
    mutationFn: async ({
      id,
      template,
    }: {
      id: string;
      template: CreateTemplateTypes;
    }) => {
      return await updateDelegationTemplate(id, template);
    },
  });

  const {
    mutate: deleteTemplate,
    isPending: isDeletingTemplate,
    isError: isErrorDeleteTemplate,
  } = useMutation({
    mutationFn: async (id: string) => {
      return await deleteDelegationTemplate(id);
    },
  });

  const {
    mutate: adoptTemplate,
    isPending: isAdoptingTemplate,
    isError: isErrorAdoptingTemplate,
  } = useMutation({
    mutationFn: async (item: AdoptTemplateTypes) => {
      return await adoptDelegationTemplate(item);
    },
  });
  return {
    templates,
    isLoading,
    isError,
    refetch,
    template,
    isLoadingTemplate,
    isErrorTemplate,
    refetchTemplate,
    createTemplate,
    isCreatingTemplate,
    isErrorCreateTemplate,
    updateTemplate,
    isUpdatingTemplate,
    isErrorUpdateTemplate,
    deleteTemplate,
    isDeletingTemplate,
    isErrorDeleteTemplate,
    adoptTemplate,
    isAdoptingTemplate,
    isErrorAdoptingTemplate,
  };
};
