import { useCallback } from 'react';
import { trpc } from '@/lib/trpc';

interface BriefingResult {
  briefingMarkdown: string;
  canvasDraft: string | null;
  canvasKind: string | null;
}

interface UseTaskBriefCacheReturn {
  getBriefing: (taskId: string) => BriefingResult | null;
  setBriefing: (taskId: string, result: BriefingResult) => void;
  isCached: (taskId: string) => boolean;
}

// Module-level session cache (cleared on carousel close via clearAll)
const sessionCache = new Map<string, BriefingResult>();

export function clearBriefingCache() {
  sessionCache.clear();
}

export function useTaskBriefCache(): UseTaskBriefCacheReturn {
  const getBriefing = useCallback((taskId: string) => {
    return sessionCache.get(taskId) ?? null;
  }, []);

  const setBriefing = useCallback((taskId: string, result: BriefingResult) => {
    sessionCache.set(taskId, result);
  }, []);

  const isCached = useCallback((taskId: string) => {
    return sessionCache.has(taskId);
  }, []);

  return { getBriefing, setBriefing, isCached };
}

// ---------------------------------------------------------------------------
// Single-task briefing hook — fetches from DB or triggers research
// ---------------------------------------------------------------------------

interface UseTaskBriefingReturn {
  briefing: BriefingResult | null;
  isResearching: boolean;
  refresh: () => void;
}

export function useTaskBriefingData(taskId: string | null): UseTaskBriefingReturn {
  const utils = trpc.useUtils();

  const dbQuery = trpc.ai.getTaskBriefing.useQuery(
    { taskId: taskId ?? '' },
    { enabled: !!taskId && !sessionCache.has(taskId ?? ''), staleTime: Infinity },
  );

  const researchMutation = trpc.ai.taskBriefResearch.useMutation();
  const isResearching = researchMutation.isPending;

  const cachedResult = taskId ? sessionCache.get(taskId) ?? null : null;

  const briefing: BriefingResult | null = cachedResult ?? (dbQuery.data
    ? {
        briefingMarkdown: dbQuery.data.briefingMarkdown,
        canvasDraft: dbQuery.data.canvasDraft ?? null,
        canvasKind: dbQuery.data.canvasKind ?? null,
      }
    : null);

  const refresh = useCallback(() => {
    if (!taskId) return;
    sessionCache.delete(taskId);
    void utils.ai.getTaskBriefing.invalidate({ taskId });
    researchMutation.mutate({ taskId, requestId: crypto.randomUUID() });
  }, [taskId, utils, researchMutation]);

  return { briefing, isResearching, refresh };
}
