/**
 * 역할·메뉴 접근 권한
 */
import type { MenuPage } from '../components/TopMenuBar';

export type UserRole = 'ADMIN' | 'USER' | 'GUEST';

export type TopMenuId = MenuPage;

export type SettingsCategoryId =
  | 'general' | 'chart' | 'indicators' | 'backtest' | 'strategy'
  | 'paper' | 'alert' | 'network' | 'admin';

export const TOP_MENU_IDS: TopMenuId[] = [
  'dashboard', 'chart', 'paper', 'strategy-editor', 'backtest', 'settings',
];

export const SETTINGS_MENU_IDS: SettingsCategoryId[] = [
  'general', 'chart', 'indicators', 'backtest', 'strategy', 'paper', 'alert', 'network', 'admin',
];

export const ALL_MENU_IDS = [
  'dashboard', 'chart', 'paper', 'strategy', 'strategy-editor', 'backtest', 'notifications', 'settings',
  ...SETTINGS_MENU_IDS.map(id => `settings_${id}` as const),
] as const;

export type MenuPermissionId = typeof ALL_MENU_IDS[number];

export const MENU_LABELS: Record<string, string> = {
  dashboard: '대시보드',
  chart: '실시간차트',
  paper: '모의투자',
  strategy: '투자전략',
  'strategy-editor': '전략편집기',
  backtest: '백테스팅',
  notifications: '알림',
  settings: '설정',
  settings_general: '설정 · 일반',
  settings_chart: '설정 · 차트',
  settings_indicators: '설정 · 보조지표',
  settings_backtest: '설정 · 백테스팅',
  settings_strategy: '설정 · 전략',
  settings_paper: '설정 · 모의투자',
  settings_alert: '설정 · 알림',
  settings_network: '설정 · 네트워크',
  settings_admin: '설정 · 관리자',
};

export const ROLE_LABELS: Record<UserRole, string> = {
  ADMIN: '관리자',
  USER: '사용자',
  GUEST: '게스트',
};

export interface MenuPermissionsDto {
  role: UserRole;
  permissions: Record<string, boolean>;
}

export function settingsCategoryToMenuId(cat: SettingsCategoryId): string {
  return `settings_${cat}`;
}

export function canAccessMenu(
  permissions: Record<string, boolean> | null | undefined,
  menuId: string,
): boolean {
  if (menuId === 'strategy') return false;
  if (!permissions) return menuId === 'chart';
  if (menuId === 'strategy-editor') {
    if (permissions['strategy-editor'] === true) return true;
    return permissions.strategy === true;
  }
  return permissions[menuId] === true;
}

export function firstAllowedTopMenu(
  permissions: Record<string, boolean> | null | undefined,
): TopMenuId {
  for (const id of TOP_MENU_IDS) {
    if (canAccessMenu(permissions, id)) return id;
  }
  return 'chart';
}

export function normalizeRole(role?: string | null): UserRole {
  const r = (role ?? 'GUEST').toUpperCase();
  if (r === 'ADMIN' || r === 'USER' || r === 'GUEST') return r;
  return 'USER';
}
