import { useMutation, useQueryClient } from "@tanstack/react-query";
import { InferRequestType, InferResponseType } from "hono";

import { client } from "@/lib/rpc";
import { toast } from "sonner";

type ResponseType = InferResponseType<typeof client.api.epics[":epicId"]["$patch"], 200>;
type RequestType = InferRequestType<typeof client.api.epics[":epicId"]["$patch"]>;

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

  const mutation = useMutation<ResponseType, Error, RequestType>({
    mutationFn: async ({ param, json }) => {
      const response = await client.api.epics[":epicId"]["$patch"]({ param, json });

      if (!response.ok) {
        throw new Error("Failed to update epic");
      }

      return await response.json();
    },
    onSuccess: ({ data }) => {
      toast.success("Epic updated");
      queryClient.invalidateQueries({ queryKey: ["epics"] });
      queryClient.invalidateQueries({ queryKey: ["epic", data.id] });
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
    },
    onError: () => {
      toast.error("Failed to update epic");
    },
  });

  return mutation;
}; 