"use client";

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

import { toggleProviderPackageApi } from "@/lib/api/catalog.api";
import { getApiErrorMessage } from "@/lib/api/error";
import { queryKeys } from "@/lib/constants/query-keys";
import { useTranslation } from "@/hooks/useTranslation";
import type { ToggleProviderPackageRequest } from "@/types/catalog";

interface ToggleProviderPackageVariables extends ToggleProviderPackageRequest {
  packageId: string;
}

/**
 * Opts the signed-in provider in or out of one catalog package.
 *
 * One hook instance serves the whole table — the package id is a mutation
 * variable, not a hook argument, so rows don't each need their own instance.
 *
 * This is also the price-change path: `optIn: true` with a new price upserts
 * it. The success copy therefore distinguishes three outcomes, since the same
 * endpoint covers all of them.
 *
 * `mutateAsync` is what callers should use from a ConfirmDialog: opting out
 * fails with 400 when past bookings reference the service, and the dialog must
 * stay open so the toast can explain that.
 */
export function useToggleProviderPackage(options?: { onSuccess?: () => void }) {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ packageId, ...payload }: ToggleProviderPackageVariables) =>
      toggleProviderPackageApi(packageId, payload),
    onSuccess: (_data, variables) => {
      toast.success(
        variables.optIn
          ? t("catalog.toast.serviceEnabled")
          : t("catalog.toast.serviceDisabled"),
      );
      queryClient.invalidateQueries({ queryKey: queryKeys.catalog.all });
      options?.onSuccess?.();
    },
    onError: (error) => {
      toast.error(getApiErrorMessage(error, t("catalog.toast.toggleFailed")));
    },
  });
}
