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

import { calcVersionProgress } from './version-progress';
import type { DevTask } from './dev-task';
import type { Requirement } from './requirement';
import type { VersionPlan } from './version-plan';

function requirement(id: string): Requirement {
  return {
    id,
    code: 'QY0001',
    title: '需求',
    description: '需求描述',
    productId: 'product-1',
    projectId: 'project-1',
    versionId: 'version-1',
    sourceType: 'internal',
    sourceTarget: '产品部',
    platforms: ['web'],
    typeId: 'type-1',
    status: 'planned',
    priority: 'P1',
    effort: 'M',
    creator: 'PM',
    createdAt: '2026-06-29',
  };
}

function plan(patch: Partial<VersionPlan>): VersionPlan {
  return {
    id: 'plan-1',
    versionId: 'version-1',
    type: 'product',
    title: '产品方案',
    owner: 'PM',
    startTime: '2026-06-29T09:00',
    endTime: '2026-06-29T18:00',
    status: 'in_progress',
    linkedRequirementIds: ['r1'],
    completedRequirementIds: ['r1'],
    createdAt: '2026-06-29',
    addedBy: 'PM',
    ...patch,
  };
}

test('version progress uses explicit requirement coverage before legacy completed ids', () => {
  const progress = calcVersionProgress(
    'version-1',
    [plan({
      requirementCoverage: [{
        requirementId: 'r1',
        status: 'partial',
        completedContent: '完成主流程',
        remainingContent: '剩余异常状态',
        updatedAt: '2026-06-29T09:00:00.000Z',
        updatedBy: 'PM',
      }],
    } as Partial<VersionPlan>)],
    [requirement('r1')],
    [],
    [],
  );

  assert.equal(progress, 0);
});

test('version progress includes no-requirement-id dev tasks by version id', () => {
  const noReqTask = {
    id: 'dev-no-req',
    taskNo: 'DEV-001',
    versionId: 'version-1',
    requirementId: '',
    requirementName: '预入职人员支持',
    title: '实现预入职人员选择',
    categoryId: 'frontend',
    assigneeId: '',
    priority: 'P1',
    expectedStartAt: '',
    expectedEndAt: '',
    status: 'submitted',
    isBlocked: false,
    createdBy: 'AI',
    createdAt: '2026-06-29T09:00:00.000Z',
    updatedAt: '2026-06-29T10:00:00.000Z',
  } as unknown as DevTask;

  const progress = calcVersionProgress('version-1', [], [], [noReqTask], []);

  assert.equal(progress, 100);
});
