import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  serviceCategoryService,
  CreateServiceCategoryRequest,
} from "../services/api/serviceCategoryService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

//  Query Keys
const SERVICE_CATEGORY_KEYS = {
  all: ["service-categories"] as const,
  list: (organizationId: string) =>
    ["service-categories", "list", organizationId] as const,
};

//  GET SERVICE CATEGORY LIST
export function useServiceCategoryList(organizationId: string) {
  return useQuery({
    queryKey: SERVICE_CATEGORY_KEYS.list(organizationId),
    queryFn: () => serviceCategoryService.getList(organizationId),
    enabled: !!organizationId,
  });
}

// 🎯 UNIFIED HOOK - Returns all service category operations in one object
export function useServiceCategoryMutations() {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const createMutation = useMutation({
    mutationFn: (data: CreateServiceCategoryRequest) =>
      serviceCategoryService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SERVICE_CATEGORY_KEYS.all });
      toast("Service Category created successfully");
    },
    onError: (exception) => {
      handleError(exception);
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: string;
      data: CreateServiceCategoryRequest;
    }) => serviceCategoryService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SERVICE_CATEGORY_KEYS.all });
      toast("Service Category updated successfully");
    },
    onError: (exception) => {
      handleError(exception);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => serviceCategoryService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SERVICE_CATEGORY_KEYS.all });
      toast("Service Category deleted successfully");
    },
    onError: (exception) => {
      handleError(exception);
    },
  });

  return {
    create: createMutation,
    update: updateMutation,
    delete: deleteMutation,
  };
}
