import { lazy, Suspense } from 'react';
import { Spin } from 'antd';
import { Route } from 'react-router-dom';

/**
 * 메뉴 코드 → React 컴포넌트 매핑.
 * 백엔드 menu 테이블의 component_path 와 1:1 대응.
 * 새 화면 추가 시 이 맵에만 등록하면 자동 라우팅된다.
 */
const componentMap: Record<string, React.LazyExoticComponent<React.ComponentType<any>>> = {
  // 조직/인사
  'org/AgentList':           lazy(() => import('@/pages/org/AgentList')),
  'org/AgentDetail':         lazy(() => import('@/pages/org/AgentDetail')),
  'org/AgentForm':           lazy(() => import('@/pages/org/AgentForm')),

  // 계약
  'product/ContractList':    lazy(() => import('@/pages/product/ContractList')),

  // 수수료규정
  'rule/CommissionRateList': lazy(() => import('@/pages/rule/CommissionRateList')),
  'rule/PayoutRuleList':     lazy(() => import('@/pages/rule/PayoutRuleList')),

  // 데이터수신
  'receive/ProfileList':     lazy(() => import('@/pages/receive/ProfileList')),
  'receive/ErrorList':       lazy(() => import('@/pages/receive/ErrorList')),

  // 원장
  'ledger/RecruitLedger':    lazy(() => import('@/pages/ledger/RecruitLedger')),
  'ledger/ExceptionLedger':  lazy(() => import('@/pages/ledger/ExceptionLedger')),

  // 정산/지급/배치
  'settle/SettleList':       lazy(() => import('@/pages/settle/SettleList')),
  'settle/PaymentList':      lazy(() => import('@/pages/settle/PaymentList')),
  'settle/BatchRun':         lazy(() => import('@/pages/settle/BatchRun')),

  // 시스템관리
  'system/UserList':         lazy(() => import('@/pages/system/UserList')),
  'system/RoleList':         lazy(() => import('@/pages/system/RoleList')),
  'system/CodeList':         lazy(() => import('@/pages/system/CodeList')),
};

export interface MenuRoute {
  menuPath: string;        // 라우트 경로 (예: 'rule/commission-rates')
  componentPath: string;   // componentMap 키 (예: 'rule/CommissionRateList')
}

/** 메뉴 목록을 받아 React Route 배열로 변환. */
export function buildDynamicRoutes(menus: MenuRoute[]) {
  return menus
    .map((m) => {
      const Cmp = componentMap[m.componentPath];
      if (!Cmp) {
        console.warn(`[router] component not found: ${m.componentPath}`);
        return null;
      }
      const path = m.menuPath.replace(/^\//, '');
      return (
        <Route
          key={path}
          path={path}
          element={
            <Suspense fallback={<Spin />}>
              <Cmp />
            </Suspense>
          }
        />
      );
    })
    .filter(Boolean);
}
