import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  approveUserPosition,
  fetchUserPositionApprovals,
  rejectUserPosition,
  type UserPositionApprovalParams,
  type UserPositionDecisionPayload,
} from "@/user-management/services/api/userPositionApprovalService";

interface DecisionVariables extends UserPositionDecisionPayload {
  id: string;
}

const QUERY_KEY = "user-position-approvals";

export const useUserPositionApprovals = (
  params: UserPositionApprovalParams = {},
) => {
  const queryClient = useQueryClient();

  const approvalsQuery = useQuery({
    queryKey: [QUERY_KEY, params],
    queryFn: () => fetchUserPositionApprovals(params),
  });

  const invalidateList = () =>
    queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });

  const approveMutation = useMutation({
    mutationFn: ({ id, comment }: DecisionVariables) =>
      approveUserPosition(id, { comment }),
    onSuccess: () => {
      toast.success("User position approved successfully");
      invalidateList();
    },
    onError: () => toast.error("Failed to approve user position"),
  });

  const rejectMutation = useMutation({
    mutationFn: ({ id, comment }: DecisionVariables) =>
      rejectUserPosition(id, { comment }),
    onSuccess: () => {
      toast.success("User position rejected successfully");
      invalidateList();
    },
    onError: () => toast.error("Failed to reject user position"),
  });

  return { approvalsQuery, approveMutation, rejectMutation };
};
