"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

import { updateProviderStatusApi } from "@/lib/api/provider.api";
import { getApiErrorMessage } from "@/lib/api/error";
import { queryKeys } from "@/lib/constants/query-keys";
import { useTranslation } from "@/hooks/useTranslation";
import type { UpdateProviderStatusRequest } from "@/types/provider";

/**
 * Account status + commission rate mutation.
 *
 * `mutateAsync` is what callers should use from a ConfirmDialog: the dialog
 * awaits it and stays open if it rejects, while the toast below explains why.
 *
 * Invalidates the whole `providers` key rather than just this provider — the
 * list rows show status and commission, so both caches go stale together.
 */
export function useUpdateProviderStatus(
  providerId: string,
  options?: { onSuccess?: () => void },
) {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (payload: UpdateProviderStatusRequest) =>
      updateProviderStatusApi(providerId, payload),
    onSuccess: (_data, variables) => {
      toast.success(
        variables.customCommissionRate !== undefined
          ? t("providers.toast.commissionUpdated")
          : t("providers.toast.statusUpdated"),
      );
      queryClient.invalidateQueries({ queryKey: queryKeys.providers.all });
      options?.onSuccess?.();
    },
    onError: (error) => {
      toast.error(getApiErrorMessage(error, t("providers.toast.statusFailed")));
    },
  });
}
