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

import {
  generateUsernameFromName,
  ensureMemberUsernames,
  type Member,
} from './members';

function member(overrides: Partial<Member>): Member {
  return {
    id: overrides.id ?? 'm-1',
    name: overrides.name ?? '张三',
    departmentId: overrides.departmentId ?? 'dept-1',
    roleId: overrides.roleId ?? 'role-dev',
    phone: overrides.phone ?? '',
    email: overrides.email ?? '',
    password: overrides.password ?? 'Ftb@2024',
    createdAt: overrides.createdAt ?? '2026-07-01',
    username: overrides.username,
  };
}

test('generateUsernameFromName uses lowercase full pinyin for Chinese names', () => {
  assert.equal(generateUsernameFromName('张三', []), 'zhangsan');
  assert.equal(generateUsernameFromName(' 欧阳娜娜 ', []), 'ouyangnana');
});

test('generateUsernameFromName appends zero-padded duplicate suffixes', () => {
  assert.equal(generateUsernameFromName('张三', ['zhangsan']), 'zhangsan1');
  assert.equal(generateUsernameFromName('张三', ['zhangsan', 'zhangsan1']), 'zhangsan01');
  assert.equal(generateUsernameFromName('张三', ['zhangsan', 'zhangsan1', 'zhangsan01']), 'zhangsan001');
});

test('generateUsernameFromName keeps existing username when editing another member', () => {
  assert.equal(generateUsernameFromName('张三', ['zhangsan'], 'lisi'), 'lisi');
});

test('ensureMemberUsernames fills missing usernames without syncing renamed members', () => {
  const result = ensureMemberUsernames([
    member({ id: 'm-1', name: '张三', username: 'lisi' }),
    member({ id: 'm-2', name: '张三' }),
  ]);

  assert.equal(result.changed, true);
  assert.equal(result.members[0].username, 'lisi');
  assert.equal(result.members[1].username, 'zhangsan');
});
