import assert from 'node:assert/strict';
import test from 'node:test';
import { buildVersionScopeTree, filterVersionsForList } from './version-list';
import type { VersionWithContext } from './derive';

function version(input: Partial<VersionWithContext> & Pick<VersionWithContext, 'id' | 'name' | 'productId' | 'productName' | 'projectId' | 'projectName'>): VersionWithContext {
  return {
    status: 'developing',
    releaseDate: null,
    createdAt: '2026-07-01T00:00:00.000Z',
    ...input,
  };
}

const versions = [
  version({ id: 'v-a', name: 'AlphaV1.0', productId: 'prod-a', productName: '产品A', projectId: 'proj-a', projectName: 'Alpha', priority: 'P1' }),
  version({ id: 'v-b', name: 'AlphaV1.1', productId: 'prod-a', productName: '产品A', projectId: 'proj-a', projectName: 'Alpha', priority: 'P2' }),
  version({ id: 'v-c', name: 'BetaV1.0', productId: 'prod-a', productName: '产品A', projectId: 'proj-b', projectName: 'Beta', priority: 'P0' }),
  version({ id: 'v-d', name: 'GammaV1.0', productId: 'prod-b', productName: '产品B', projectId: 'proj-c', projectName: 'Gamma', priority: 'P3' }),
];

test('buildVersionScopeTree groups versions by product and project with counts', () => {
  const tree = buildVersionScopeTree(versions, '');

  assert.equal(tree.length, 2);
  assert.equal(tree[0].count, 3);
  assert.equal(tree[0].projects[0].count, 2);
  assert.equal(tree[0].projects[1].count, 1);
});

test('buildVersionScopeTree filters the tree by product project or version keyword', () => {
  assert.deepEqual(buildVersionScopeTree(versions, 'Beta').map((node) => node.projects.map((project) => project.projectName)), [['Beta']]);
  assert.deepEqual(buildVersionScopeTree(versions, 'GammaV1.0').map((node) => node.productName), ['产品B']);
});

test('filterVersionsForList applies scope keyword and priority filters', () => {
  assert.deepEqual(
    filterVersionsForList(versions, { scope: { type: 'project', projectId: 'proj-a' }, keyword: '1.1', priority: 'all' }).map((item) => item.id),
    ['v-b'],
  );

  assert.deepEqual(
    filterVersionsForList(versions, { scope: { type: 'product', productId: 'prod-a' }, keyword: '', priority: 'P0' }).map((item) => item.id),
    ['v-c'],
  );
});
