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

import { findMemberByUsernameCredentials, resolveAuthUserFromMembers, toAuthUser, type AuthUser } from './auth-user';
import type { Member } from './members';

const member: Member = {
  id: 'm-8',
  name: '超级管理员',
  username: 'admin',
  departmentId: '',
  roleId: 'role-admin',
  phone: '13200132008',
  email: '',
  password: 'Ftb@2024',
  createdAt: '2024-01-01',
};

test('toAuthUser removes password and keeps stable member identity', () => {
  assert.deepEqual(toAuthUser(member), {
    id: 'm-8',
    name: '超级管理员',
    username: 'admin',
    departmentId: '',
    roleId: 'role-admin',
    email: '',
  });
});

test('resolveAuthUserFromMembers refreshes stale display names by member id', () => {
  const staleUser: AuthUser = {
    id: 'm-8',
    name: '陈十',
    username: 'chenshi',
    departmentId: '',
    roleId: 'role-admin',
    email: 'old@company.com',
  };

  const resolved = resolveAuthUserFromMembers(staleUser, [member]);

  assert.equal(resolved?.id, 'm-8');
  assert.equal(resolved?.name, '超级管理员');
  assert.equal(resolved?.username, 'admin');
  assert.equal(resolved?.email, '');
});

test('resolveAuthUserFromMembers returns null when the account no longer exists', () => {
  const staleUser: AuthUser = {
    id: 'm-9',
    name: '离职用户',
    username: 'lizhiyonghu',
    departmentId: 'dept-2',
    roleId: 'role-dev',
    email: 'old@company.com',
  };

  assert.equal(resolveAuthUserFromMembers(staleUser, [member]), null);
});

test('findMemberByUsernameCredentials uses username instead of phone for login', () => {
  const matched = findMemberByUsernameCredentials('admin', 'Ftb@2024', [member]);

  assert.equal(matched?.id, 'm-8');
  assert.equal(findMemberByUsernameCredentials('13200132008', 'Ftb@2024', [member]), null);
});
