import { useQuery, keepPreviousData } from '@tanstack/react-query';
import {
  fetchLocalTask,
  fetchLocalTaskComments,
  fetchLocalFiles,
  fetchLocalFileContent,
} from '../api';
import { POLLING } from '../lib/constants.js';

// Note: no placeholderData here. We deliberately let task-switching flush the
// previous task's data so the UI shows <SkeletonChatPane /> while the new
// task loads — otherwise the chat keeps rendering the old task's title and
// messages until the fetch resolves, which is confusing. Same-key refetches
// (polling, mutation invalidation) are unaffected; React Query keeps cached
// data during same-key refetches regardless of placeholderData.
export function useLocalTask(taskId: number | null, enabled: boolean) {
  return useQuery({
    queryKey: ['localTask', taskId],
    queryFn: () => fetchLocalTask(taskId!),
    enabled: enabled && taskId !== null,
    refetchInterval: enabled ? POLLING.FAST : false,
  });
}

export function useLocalTaskComments(taskId: number | null, enabled: boolean) {
  return useQuery({
    queryKey: ['localTaskComments', taskId],
    queryFn: () => fetchLocalTaskComments(taskId!),
    enabled: enabled && taskId !== null,
    refetchInterval: enabled ? POLLING.FAST : false,
  });
}

export function useLocalActivityLog(taskId: number | null, enabled: boolean) {
  return useQuery({
    queryKey: ['localActivityLog', taskId],
    queryFn: async () => {
      const logFiles = await fetchLocalFiles(taskId!, 'logs', '');
      const activityEntry = logFiles.entries.find(
        e => e.kind === 'file' && e.name === 'activity.log',
      );
      if (!activityEntry) return '';
      try {
        return await fetchLocalFileContent(taskId!, 'logs', activityEntry.path);
      } catch {
        return '';
      }
    },
    enabled: enabled && taskId !== null,
    refetchInterval: enabled ? POLLING.FAST : false,
    placeholderData: keepPreviousData,
  });
}
