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

import type { Requirement } from './requirement';
import {
  getRequirementVersionSelectionPatch,
  getRequirementVersionUnlinkPatch,
} from './requirement-version-link';

function requirement(patch: Partial<Requirement> = {}): Requirement {
  return {
    id: 'req-1',
    code: 'REQ-001',
    title: 'Requirement',
    description: '',
    productId: 'product-1',
    projectId: 'project-1',
    versionId: 'version-1',
    sourceType: 'internal',
    sourceTarget: '',
    platforms: [],
    typeId: 'type-1',
    status: 'planned',
    priority: 'P2',
    effort: 'M',
    creator: 'tester',
    createdAt: '2026-07-02T00:00:00.000Z',
    addedToVersionBy: 'pm',
    ...patch,
  };
}

test('unlinking a version-scoped requirement returns it to adopted', () => {
  for (const status of ['planned', 'developing', 'testing', 'released'] as const) {
    assert.deepEqual(getRequirementVersionUnlinkPatch(requirement({ status })), {
      versionId: undefined,
      addedToVersionBy: undefined,
      status: 'adopted',
    });
  }
});

test('unlinking keeps other requirement statuses unchanged', () => {
  assert.deepEqual(getRequirementVersionUnlinkPatch(requirement({ status: 'adopted' })), {
    versionId: undefined,
    addedToVersionBy: undefined,
  });
});

test('clearing version from requirement edit uses the same unlink semantics', () => {
  assert.deepEqual(getRequirementVersionSelectionPatch(requirement(), ''), {
    versionId: undefined,
    addedToVersionBy: undefined,
    status: 'adopted',
  });
});

test('selecting a version preserves the current business status', () => {
  assert.deepEqual(getRequirementVersionSelectionPatch(requirement({ status: 'adopted' }), 'version-2', 'pm2'), {
    versionId: 'version-2',
    addedToVersionBy: 'pm2',
  });
});
