import assert from 'node:assert/strict';
import test from 'node:test';
import type { RoleItem } from './members';
import { DEFAULT_ROLE_PERMISSIONS } from './permissions';
import { mergePresetRolePermissions } from './role-permission-migration';

test('default group leader role has business permissions without admin modules', () => {
  const permissions = DEFAULT_ROLE_PERMISSIONS['role-lead'];

  assert.ok(permissions);
  assert.ok(permissions.includes('overtime:view'));
  assert.ok(!permissions.includes('*'));
  assert.equal(permissions.some((p) => p.startsWith('member:')), false);
  assert.equal(permissions.some((p) => p.startsWith('role:')), false);
});

test('mergePresetRolePermissions adds the built-in group leader role to old role data', () => {
  const roles: RoleItem[] = [
    {
      id: 'role-pm',
      name: 'Product Manager',
      createdAt: '2024-01-01',
      permissions: ['product:view'],
    },
  ];

  const result = mergePresetRolePermissions(roles);
  const lead = result.roles.find((role) => role.id === 'role-lead');

  assert.equal(result.changed, true);
  assert.ok(lead);
  assert.equal(lead.name, '组长');
  assert.deepEqual(lead.permissions, DEFAULT_ROLE_PERMISSIONS['role-lead']);
});

test('mergePresetRolePermissions adds new preset permissions to existing product manager role', () => {
  const roles: RoleItem[] = [
    {
      id: 'role-pm',
      name: '产品经理',
      createdAt: '2024-01-01',
      permissions: ['product:view'],
    },
  ];

  const result = mergePresetRolePermissions(roles);

  assert.equal(result.changed, true);
  assert.ok(result.roles[0].permissions.includes('product:view'));
  assert.ok(result.roles[0].permissions.includes('xiaobao.warning:view'));
  assert.ok(result.roles[0].permissions.includes('xiaobao.warning:manage'));
});

test('mergePresetRolePermissions keeps custom role permissions unchanged', () => {
  const roles: RoleItem[] = [
    {
      id: 'role-custom',
      name: '自定义角色',
      createdAt: '2024-01-01',
      permissions: ['version:view'],
    },
  ];

  const result = mergePresetRolePermissions(roles);

  assert.equal(result.changed, false);
  assert.deepEqual(result.roles[0].permissions, ['version:view']);
});

test('mergePresetRolePermissions does not restore unrelated default permissions removed from preset roles', () => {
  const roles: RoleItem[] = [
    {
      id: 'role-pm',
      name: '产品经理',
      createdAt: '2024-01-01',
      permissions: ['product:view'],
    },
  ];

  const result = mergePresetRolePermissions(roles);

  assert.equal(result.changed, true);
  assert.deepEqual(result.roles[0].permissions, [
    'product:view',
    'xiaobao.warning:view',
    'xiaobao.warning:manage',
  ]);
});
