import test from 'node:test'
import assert from 'node:assert/strict'
import { buildAppModuleGraph } from './appModuleGraph.js'

test('buildAppModuleGraph creates role and menu module nodes with access edges', () => {
  const graph = buildAppModuleGraph({
    roles: [
      { code: 'reader', name: '读者', description: '前台用户' },
      { code: 'admin', name: '管理员', description: '后台运营' }
    ],
    frontendMenus: [
      {
        code: 'catalog',
        name: '图书目录',
        path: '/catalog',
        requiresLogin: false,
        visibleRoles: [],
        dataScope: 'PUBLIC'
      },
      {
        code: 'my_borrows',
        name: '我的借阅',
        path: '/my-borrows',
        requiresLogin: true,
        visibleRoles: ['reader'],
        dataScope: 'CURRENT_USER'
      }
    ],
    adminMenus: [
      {
        code: 'book_admin',
        name: '图书管理',
        path: '/admin/books',
        requiresLogin: true,
        visibleRoles: ['admin'],
        dataScope: 'ROLE'
      }
    ]
  })

  assert.deepEqual(
    graph.nodes.map((node) => ({ id: node.id, title: node.title, kind: node.kind, lane: node.lane })),
    [
      { id: 'access:public', title: '公开访问', kind: 'access', lane: 'access' },
      { id: 'role:reader', title: '读者', kind: 'role', lane: 'role' },
      { id: 'role:admin', title: '管理员', kind: 'role', lane: 'role' },
      { id: 'frontend:catalog', title: '图书目录', kind: 'menu', lane: 'frontend' },
      { id: 'frontend:my_borrows', title: '我的借阅', kind: 'menu', lane: 'frontend' },
      { id: 'admin:book_admin', title: '图书管理', kind: 'menu', lane: 'admin' }
    ]
  )

  assert.deepEqual(
    graph.edges.map((edge) => ({ source: edge.source, target: edge.target, label: edge.label })),
    [
      { source: 'access:public', target: 'frontend:catalog', label: 'PUBLIC' },
      { source: 'role:reader', target: 'frontend:my_borrows', label: 'CURRENT_USER' },
      { source: 'role:admin', target: 'admin:book_admin', label: 'ROLE' }
    ]
  )
})

test('buildAppModuleGraph creates a logged-in access node for menus without explicit visible roles', () => {
  const graph = buildAppModuleGraph({
    roles: [],
    frontendMenus: [
      {
        code: 'profile',
        name: '个人中心',
        path: '/profile',
        requiresLogin: true,
        visibleRoles: [],
        dataScope: 'CURRENT_USER'
      }
    ],
    adminMenus: []
  })

  assert.equal(graph.nodes[0].id, 'access:logged_in')
  assert.equal(graph.edges[0].source, 'access:logged_in')
  assert.equal(graph.edges[0].target, 'frontend:profile')
})
