import test from 'node:test';
import assert from 'node:assert/strict';
import { aggregateWorkItems, getWorkspacePendingCount, getWorkspacePendingCountByVersion } from './workspace-engine';
import type { DevTask } from './dev-task';

test('getWorkspacePendingCount counts unfinished work items only', () => {
  const count = getWorkspacePendingCount([
    { completed: false },
    { completed: true },
    { completed: false },
  ]);

  assert.equal(count, 2);
});

test('getWorkspacePendingCountByVersion counts unfinished work items in one pass', () => {
  const counts = getWorkspacePendingCountByVersion([
    { versionId: 'ver-1', completed: false },
    { versionId: 'ver-1', completed: true },
    { versionId: 'ver-2', completed: false },
    { versionId: '', completed: false },
  ]);

  assert.equal(counts.get('ver-1'), 1);
  assert.equal(counts.get('ver-2'), 1);
  assert.equal(counts.has(''), false);
});

test('aggregateWorkItems returns no items before the current user is known', () => {
  const unassignedTask = {
    id: 'dev-unassigned',
    taskNo: 'DEV-002',
    versionId: 'ver-1',
    requirementId: '',
    title: 'Unassigned task',
    categoryId: 'frontend',
    assigneeId: '',
    priority: 'P1',
    expectedStartAt: '',
    expectedEndAt: '',
    status: 'todo',
    isBlocked: false,
    createdBy: 'AI',
    createdAt: '2026-06-29T09:00:00.000Z',
    updatedAt: '2026-06-29T09:00:00.000Z',
  } as DevTask;

  const items = aggregateWorkItems(
    '',
    [],
    [unassignedTask],
    [],
    [],
    new Map([['ver-1', { id: 'ver-1', name: 'V1.0', productName: 'FTB', projectName: 'PM' }]]),
    new Map(),
  );

  assert.deepEqual(items, []);
});

test('aggregateWorkItems uses direct version id for no-requirement dev tasks', () => {
  const task = {
    id: 'dev-no-req',
    taskNo: 'DEV-001',
    versionId: 'ver-1',
    requirementId: '',
    requirementName: '预入职人员支持',
    title: '实现预入职人员选择',
    categoryId: 'frontend',
    assigneeId: '张三',
    priority: 'P1',
    expectedStartAt: '',
    expectedEndAt: '',
    status: 'todo',
    isBlocked: false,
    createdBy: 'AI',
    createdAt: '2026-06-29T09:00:00.000Z',
    updatedAt: '2026-06-29T09:00:00.000Z',
  } as DevTask;

  const items = aggregateWorkItems(
    '张三',
    [],
    [task],
    [],
    [],
    new Map([['ver-1', { id: 'ver-1', name: 'V1.0', productName: 'FTB', projectName: 'PM' }]]),
    new Map(),
  );

  assert.equal(items[0].versionId, 'ver-1');
  assert.equal(items[0].versionName, 'V1.0');
});
