"use client";

import moment from "moment";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useClock } from "@/hooks/useClock";
import { useAuthStore } from "@/store/authStore";
import { getEventById } from "@/features/events/services/eventsApi";
import { getOpportunityById } from "@/features/opportunities/services/opportunities";
import { getLearnServeOpportunityById } from "@/features/opportunities/services/learnServe";
import { deletionAccessError, type DeletionKind, type DeletionSource } from "./deletionAccess";

export function useDeletionSource(id: string, type: DeletionKind, requestOnly: boolean) {
  const { t } = useTranslation();
  const userId = useAuthStore(state => state.user?.id);
  const clock = useClock(1000);
  const query = useQuery<DeletionSource>({
    queryKey: ["deletion-source", type, id, userId],
    queryFn: async () => (type === "event" ? await getEventById({ id, passToken: true })
      : type === "learnserve" ? await getLearnServeOpportunityById(id) : await getOpportunityById(id, true)).data,
    enabled: Boolean(id && userId),
    staleTime: 0,
  });
  const errorKey = deletionAccessError({ id, type, requestOnly, source: query.data, userId }, moment(clock));
  const guard = async () => {
    const latest = await query.refetch();
    const sessionChanged = String(userId ?? "") !== String(useAuthStore.getState().user?.id ?? "");
    const refusal = latest.isError || sessionChanged ? "COMMON.PUBLISH_SOURCE_UNAVAILABLE" : deletionAccessError({
      id, type, requestOnly, source: latest.data, userId: useAuthStore.getState().user?.id,
    });
    if (refusal) { toast.error(t(refusal)); return false; }
    return true;
  };
  return { query, errorKey, loading: !clock || (Boolean(userId) && query.isPending), guard };
}
