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

import { filterMembersForList, getDisplayedAccountPassword, resolveLatestEditingMember } from './member-list';
import type { Department, Member } from './members';

const departments: Department[] = [
  { id: 'dept-1', name: '产品部', order: 1, createdAt: '2024-01-01' },
  { id: 'dept-2', name: '技术部', order: 2, createdAt: '2024-01-01' },
  { id: 'dept-2-1', name: '前端组', parentId: 'dept-2', order: 1, createdAt: '2024-01-01' },
];

function member(id: string, name: string, departmentId: string): Member {
  return {
    id,
    name,
    username: name.toLowerCase(),
    departmentId,
    roleId: 'role-dev',
    phone: '',
    email: '',
    password: 'Ftb@2024',
    createdAt: '2024-01-01',
  };
}

test('filterMembersForList matches member name keywords within the selected department tree', () => {
  const members = [
    member('m-1', '张三', 'dept-1'),
    member('m-2', '李四', 'dept-2-1'),
    member('m-3', '李四方', 'dept-2'),
    member('m-4', '王五', ''),
  ];

  const result = filterMembersForList({
    members,
    departments,
    activeDeptId: 'dept-2',
    nameKeyword: '李四',
  });

  assert.deepEqual(result.map((item) => item.id), ['m-2', 'm-3']);
});

test('filterMembersForList keeps unassigned admin visible only in all members when searching by name', () => {
  const members = [
    member('m-8', '超级管理员', ''),
    member('m-1', '张三', 'dept-1'),
  ];

  const allResult = filterMembersForList({
    members,
    departments,
    activeDeptId: null,
    nameKeyword: '超级',
  });
  const deptResult = filterMembersForList({
    members,
    departments,
    activeDeptId: 'dept-1',
    nameKeyword: '超级',
  });

  assert.deepEqual(allResult.map((item) => item.id), ['m-8']);
  assert.deepEqual(deptResult, []);
});

test('resolveLatestEditingMember uses the current member record for password display', () => {
  const selected = member('m-1', '张三', 'dept-1');
  const latest = { ...selected, password: 'New@2026' };

  assert.equal(resolveLatestEditingMember(selected, [latest])?.password, 'New@2026');
});

test('getDisplayedAccountPassword shows the latest member password before generated fallback', () => {
  assert.equal(getDisplayedAccountPassword(member('m-1', '张三', 'dept-1'), 'Generated@2026'), 'Ftb@2024');
  assert.equal(getDisplayedAccountPassword(null, 'Generated@2026'), 'Generated@2026');
});
