import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  fetchMyCollaborations,
  getCollaborationByRecordId,
  signRecordCollaborator,
  CollaborationDto,
  MyCollaborationsQuery,
  SignRecordCollaboratorPayload,
  CollaborationListResponse,
} from "@/record-management/services/api/collaborationService";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { MeDto } from "@/shared/dto/user/meDto";
import { useUserDetail } from "./useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";

export const useMyCollaborations = (queryParams?: MyCollaborationsQuery) => {
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const RO = permissionKeys.includes("can:dispatchRecords");
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const query = useQuery({
    queryKey: ["my-collaborations", queryParams],
    queryFn: () => fetchMyCollaborations(!RO ? queryParams : {}),
    staleTime: 5 * 60 * 1000,
    enabled: Boolean(!RO),
  });

  const signMutation = useMutation({
    mutationFn: ({ payload }: { payload: SignRecordCollaboratorPayload }) =>
      signRecordCollaborator(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["my-collaborations"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  return {
    ...query,
    signCollaboration: signMutation.mutateAsync,
    signStatus: {
      isLoading: signMutation.isPending,
      isError: signMutation.isError,
      error: signMutation.error,
    },
  };
};

export const useCollaborationByRecordId = (
  recordId?: string,
  options?: { enabled?: boolean },
) => {
  return useQuery<CollaborationListResponse>({
    queryKey: ["collaboration-by-record", recordId],
    queryFn: () => getCollaborationByRecordId(recordId as string),
    enabled: (options?.enabled ?? true) && !!recordId,
    staleTime: 0,
  });
};
