import { describe, expect, it, vi } from 'vitest';

import { shouldPollTaskDetail, taskDetailDurationMs } from '@/lib/task-detail-refresh';
import type { BackendTask } from '@/types';

const baseTask: BackendTask = {
  task_id: 'task-1',
  session_id: 'web:test',
  description: '查找餐厅',
  goal: '查找餐厅',
  constraints: [],
  priority: 0,
  status: 'running',
  creator: 'main-agent',
  created_at: '2026-05-27T02:02:41.000Z',
  updated_at: '2026-05-27T02:02:41.500Z',
  run_ids: [],
  skill_names: [],
  feedback: [],
  metadata: {},
};

describe('task detail refresh helpers', () => {
  it('polls executing task details regardless of websocket status', () => {
    expect(shouldPollTaskDetail({ ...baseTask, status: 'running' })).toBe(true);
    expect(shouldPollTaskDetail({ ...baseTask, status: 'open' })).toBe(true);
    expect(shouldPollTaskDetail({ ...baseTask, status: 'awaiting_acceptance' })).toBe(false);
    expect(shouldPollTaskDetail({ ...baseTask, status: 'closed' })).toBe(false);
  });

  it('uses current time for active task duration instead of stale updated_at', () => {
    vi.setSystemTime(new Date('2026-05-27T02:03:41.000Z'));

    expect(taskDetailDurationMs(baseTask)).toBe(60_000);
    expect(taskDetailDurationMs({ ...baseTask, status: 'awaiting_acceptance', updated_at: '2026-05-27T02:10:55.000Z' })).toBe(494_000);
  });
});
