import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  applicationService,
  CreateApplicationDto,
  UpdateApplicationDto,
} from "@/user-management/services/api/applicationService";
import {
  ApplicationDto,
  ApplicationListResponse,
} from "@/user-management/dto/applications/applicationDto";

export const useApplications = () => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const { data, isLoading, isError, refetch } =
    useQuery<ApplicationListResponse>({
      queryKey: ["applications"],
      queryFn: () => applicationService.getAll().then((res) => res.data),
      staleTime: 1000 * 60 * 5,
    });

  const createApplication = useMutation({
    mutationFn: (payload: CreateApplicationDto) =>
      applicationService.create(payload),
    onSuccess: () => {
      toast.success("Application created");
      queryClient.invalidateQueries({ queryKey: ["applications"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const updateApplication = useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateApplicationDto }) =>
      applicationService.update(id, data),
    onSuccess: () => {
      toast.success("Application updated");
      queryClient.invalidateQueries({ queryKey: ["applications"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const deleteApplication = useMutation({
    mutationFn: (id: string) => applicationService.delete(id),
    onSuccess: () => {
      toast.success("Application deleted");
      queryClient.invalidateQueries({ queryKey: ["applications"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    applications: data?.items ?? [],
    applicationsResponse: data,
    isLoading,
    isError,
    refetch,
    createApplication,
    updateApplication,
    deleteApplication,
  };
};
