import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { UseMutationResult } from "@tanstack/react-query";
import { invitePartner, updatePartner, resendInvitePartner } from "../services/auth-api";
import type { InviteResponse, InviteParams, UpdatePartnerParams, Partner } from "../services/auth-api";
import { PARTNERS_QUERY_KEYS } from "./use-partners-query";

export const useInvitePartnerMutation = (): UseMutationResult<
  InviteResponse,
  Error,
  InviteParams
> => {
  const queryClient = useQueryClient();

  return useMutation<InviteResponse, Error, InviteParams>({
    mutationFn: (params: InviteParams) => invitePartner(params),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: PARTNERS_QUERY_KEYS.list(),
      });
    },
  });
};

export const useUpdatePartnerMutation = (): UseMutationResult<
  Partner,
  Error,
  { partnerId: string; params: UpdatePartnerParams }
> => {
  const queryClient = useQueryClient();

  return useMutation<Partner, Error, { partnerId: string; params: UpdatePartnerParams }>({
    mutationFn: ({ partnerId, params }) => updatePartner(partnerId, params),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: PARTNERS_QUERY_KEYS.list(),
      });
    },
  });
};

export const useResendInviteMutation = (): UseMutationResult<
  { success: boolean },
  Error,
  string
> => {
  const queryClient = useQueryClient();

  return useMutation<{ success: boolean }, Error, string>({
    mutationFn: (partnerId: string) => resendInvitePartner(partnerId),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: PARTNERS_QUERY_KEYS.list(),
      });
    },
  });
};
