import { useQuery } from "@tanstack/react-query";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { getPositionTypeConfigurationsByUnitId } from "@/user-management/services/api/positionTypeConfigurationService";

const FIVE_MIN = 5 * 60 * 1000;

const useCanAssignRecord = () => {
  const { selectedPosition } = useAuthUser();
  const positionTypeId = selectedPosition?.positionType?.id ?? null;

  const { data } = useQuery({
    queryKey: ["positionTypeConfigurations", positionTypeId],
    queryFn: async () => {
      const res = await getPositionTypeConfigurationsByUnitId(positionTypeId!);
      return res.data;
    },
    enabled: !!positionTypeId,
    staleTime: FIVE_MIN,
  });

  const config = data?.items?.[0];

  // No config exists → allow by default; explicit false → deny
  const canAssignRecord = !config || config.canAssignRecord !== false;

  return { canAssignRecord };
};

export default useCanAssignRecord;
