import test from 'node:test';
import assert from 'node:assert/strict';

import type { DevTask } from './dev-task';
import { buildRequirementDevStatusMap, canEditRequirement } from './linkage-engine';
import * as linkageEngine from './linkage-engine';

function task(patch: Partial<DevTask> = {}): DevTask {
  return {
    id: 'task-1',
    taskNo: 'DEV-001',
    requirementId: 'req-1',
    title: 'Implement requirement',
    categoryId: 'cat-frontend',
    assigneeId: 'Alice',
    priority: 'P2',
    expectedStartAt: '2026-06-25T01:00:00.000Z',
    expectedEndAt: '2026-06-25T02:00:00.000Z',
    status: 'todo',
    isBlocked: false,
    createdBy: 'PM',
    createdAt: '2026-06-25T00:00:00.000Z',
    updatedAt: '2026-06-25T00:00:00.000Z',
    ...patch,
  };
}

test('completed requirement development status cannot be edited', () => {
  assert.equal(canEditRequirement('req-1', [task({ status: 'submitted' })]), false);
});

test('active or completed requirement development status cannot be closed', () => {
  const canCloseRequirement = (linkageEngine as any).canCloseRequirement;

  assert.equal(typeof canCloseRequirement, 'function');
  assert.equal(canCloseRequirement('req-1', [task({ status: 'in_progress' })]), false);
  assert.equal(canCloseRequirement('req-1', [task({ status: 'testing' })]), false);
  assert.equal(canCloseRequirement('req-1', [task({ status: 'submitted' })]), false);
});

test('buildRequirementDevStatusMap derives every requirement status in one pass', () => {
  const statusMap = buildRequirementDevStatusMap([
    task({ id: 'task-todo', requirementId: 'req-todo', status: 'todo' }),
    task({ id: 'task-active', requirementId: 'req-active', status: 'in_progress' }),
    task({ id: 'task-testing', requirementId: 'req-active', status: 'testing' }),
    task({ id: 'task-done-1', requirementId: 'req-done', status: 'submitted' }),
    task({ id: 'task-done-2', requirementId: 'req-done', status: 'submitted' }),
    task({ id: 'task-no-req', requirementId: '', status: 'submitted' }),
  ]);

  assert.equal(statusMap.get('req-todo'), 'todo');
  assert.equal(statusMap.get('req-active'), 'developing');
  assert.equal(statusMap.get('req-done'), 'completed');
  assert.equal(statusMap.has(''), false);
});
