import { describe, expect, it } from 'vitest';
import type { components } from '../api/schema.generated';
import { frontendPathForMenu, visibleNavigationPaths } from './AppLayout';

type BackofficeMenuItem = components['schemas']['BackofficeMenuItem'];

function menu(path: string, permissionCode: string, isActive = true): BackofficeMenuItem {
  return {
    id: crypto.randomUUID(),
    code: `menu.${path}`,
    parentCode: null,
    title: path,
    area: 0,
    path,
    icon: null,
    permissionCode,
    sortOrder: 10,
    isActive,
  };
}

describe('平台导航授权', () => {
  it('将后端平台菜单路径转换为当前前端路由', () => {
    expect(frontendPathForMenu('/platform/dashboard')).toBe('/');
    expect(frontendPathForMenu('/platform/tenants')).toBe('/tenants');
    expect(frontendPathForMenu('/platform/question-banks/')).toBe('/question-banks');
    expect(frontendPathForMenu('/platform/saas')).toBe('/subscriptions');
    expect(frontendPathForMenu('/platform/payment-settings')).toBe('/payments');
  });

  it('显示后端返回的带平台前缀菜单', () => {
    const granted = new Set(['platform:dashboard:view', 'platform:tenant:manage', 'platform:payment:read']);
    const paths = visibleNavigationPaths([
      menu('/platform/dashboard', 'platform:dashboard:view'),
      menu('/platform/tenants', 'platform:tenant:manage'),
      menu('/platform/payment-settings', 'platform:payment:read'),
    ], (...permissions) => permissions.some((permission) => granted.has(permission)));

    expect(paths).toEqual(['/', '/tenants', '/payments']);
  });

  it('同时以 ui-bootstrap 菜单和权限作为可见性边界', () => {
    const granted = new Set(['platform:dashboard:view', 'platform:tenant:manage', 'platform:audit:view']);
    const paths = visibleNavigationPaths([
      menu('/', 'platform:dashboard:view'),
      menu('/tenants', 'platform:tenant:manage'),
      menu('/audit', 'platform:audit:view', false),
    ], (...permissions) => permissions.some((permission) => granted.has(permission)));

    expect(paths).toEqual(['/', '/tenants']);
  });

  it('数据库未返回的菜单不会因本地路由定义而出现', () => {
    const paths = visibleNavigationPaths(
      [menu('/', 'platform:dashboard:view')],
      () => true,
    );

    expect(paths).toEqual(['/']);
  });
});
