import * as React from "react";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useInteractionMutations } from "../../../../../components/detail/hooks/useInteractionMutations.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const plannedActivitiesCache = /* @__PURE__ */ new Map();
function fetchPlannedActivities(dealId, useCache) {
  const url = `/api/customers/interactions?dealId=${encodeURIComponent(dealId)}&status=planned&excludeInteractionType=task&limit=100&sortField=scheduledAt&sortDir=asc`;
  const cached = plannedActivitiesCache.get(url);
  if (useCache && cached) return cached.promise;
  const entry = {
    promise: readApiResultOrThrow(url).then((result) => Array.isArray(result.items) ? result.items : [])
  };
  if (useCache) plannedActivitiesCache.set(url, entry);
  return entry.promise.finally(() => {
    if (plannedActivitiesCache.get(url) === entry) plannedActivitiesCache.delete(url);
  });
}
function useDealActivities({
  dealId,
  runMutationWithContext
}) {
  const [plannedActivities, setPlannedActivities] = React.useState([]);
  const [activityRefreshKey, setActivityRefreshKey] = React.useState(0);
  const loadPlannedActivities = React.useCallback(async (options = {}) => {
    if (!dealId) return;
    try {
      const items = await fetchPlannedActivities(dealId, options.cache === true);
      setPlannedActivities(items);
    } catch (err) {
      logger.warn("load planned activities failed", { component: "deals.detail", err });
      setPlannedActivities([]);
    }
  }, [dealId]);
  const handleActivityCreated = React.useCallback(async () => {
    setActivityRefreshKey((value) => value + 1);
    await loadPlannedActivities();
  }, [loadPlannedActivities]);
  const { completeInteraction, cancelInteraction } = useInteractionMutations({
    runMutationWithContext,
    onAfterChange: handleActivityCreated,
    logContext: "customers.deals.detail"
  });
  return {
    plannedActivities,
    activityRefreshKey,
    loadPlannedActivities,
    handleActivityCreated,
    handleMarkDone: completeInteraction,
    handleCancelActivity: cancelInteraction
  };
}
export {
  useDealActivities
};
//# sourceMappingURL=useDealActivities.js.map
