export const permissionResources = [
  { resource: 'catalog/categories', name: '分类管理', actions: ['read', 'write'] },
  { resource: 'catalog/products', name: '商品管理', actions: ['read', 'write'] },
  { resource: 'orders', name: '订单管理', actions: ['read', 'write'] },
  { resource: 'order-logs', name: '日志查询', actions: ['read', 'write'] },
  { resource: 'admin/users', name: '用户管理', actions: ['read', 'write'] },
  { resource: 'admin/audit-logs', name: '操作日志', actions: ['read'] },
  { resource: 'admin/api-call-logs', name: '接口日志', actions: ['read'] },
  { resource: 'admin/third-party', name: '第三方接口', actions: ['read', 'write'] },
  { resource: 'admin/permissions', name: '权限配置', actions: ['read', 'write'] },
];

export function normalizePermissions(permissions: Record<string, string[]>) {
  const allowedResources = new Set(
    permissionResources.map((item) => item.resource),
  );
  const allowedActionsByResource = new Map(
    permissionResources.map((item) => [item.resource, new Set(item.actions)]),
  );
  const normalized: Record<string, string[]> = {};

  for (const [resource, actions] of Object.entries(permissions || {})) {
    if (!allowedResources.has(resource) || !Array.isArray(actions)) {
      continue;
    }

    const allowedActions = allowedActionsByResource.get(resource);
    const nextActions = Array.from(
      new Set(actions.filter((action) => allowedActions?.has(action))),
    );
    if (nextActions.length) {
      normalized[resource] = nextActions;
    }
  }

  return normalized;
}
