-- ============================================================================
-- V020: 메뉴 설정 SSOT 테이블
-- 프론트엔드 사이드바 + 라우팅 + 권한 매핑의 단일 진실 공급원
-- ============================================================================

CREATE TABLE kcg.menu_config (
    menu_cd         VARCHAR(100) PRIMARY KEY,
    parent_menu_cd  VARCHAR(100) REFERENCES kcg.menu_config(menu_cd) ON DELETE CASCADE,
    menu_type       VARCHAR(10)  NOT NULL DEFAULT 'ITEM',
    url_path        VARCHAR(200),
    rsrc_cd         VARCHAR(100) REFERENCES kcg.auth_perm_tree(rsrc_cd),
    component_key   VARCHAR(150),
    icon            VARCHAR(50),
    label_key       VARCHAR(100),
    divider_label   VARCHAR(100),
    menu_level      INT NOT NULL DEFAULT 0,
    sort_ord        INT NOT NULL DEFAULT 0,
    use_yn          VARCHAR(1)  NOT NULL DEFAULT 'Y',
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

COMMENT ON TABLE  kcg.menu_config IS '메뉴 레이아웃 SSOT — 사이드바, 라우팅, 경로→권한 매핑 구동';
COMMENT ON COLUMN kcg.menu_config.menu_type IS 'ITEM(네비게이션) | GROUP(접기/펼치기) | DIVIDER(서브그룹 라벨)';
COMMENT ON COLUMN kcg.menu_config.rsrc_cd IS 'auth_perm_tree FK. 권한 체크용. GROUP/DIVIDER는 NULL';
COMMENT ON COLUMN kcg.menu_config.component_key IS '프론트 COMPONENT_REGISTRY 키. GROUP/DIVIDER는 NULL';
COMMENT ON COLUMN kcg.menu_config.use_yn IS 'Y=사이드바+라우트, H=라우트만(숨김), N=비활성';

CREATE INDEX idx_menu_config_parent ON kcg.menu_config(parent_menu_cd);
CREATE INDEX idx_menu_config_sort   ON kcg.menu_config(menu_level, sort_ord);
CREATE INDEX idx_menu_config_rsrc   ON kcg.menu_config(rsrc_cd);

-- ============================================================================
-- 시드 데이터: 현재 NAV_ENTRIES + Route 정의 기반 35건
-- sort_ord 100 간격 (삽입 여유)
-- ============================================================================

-- ─── Top-level ITEM (13개) ─────────────────────────────────────────────────
INSERT INTO kcg.menu_config(menu_cd, parent_menu_cd, menu_type, url_path, rsrc_cd, component_key, icon, label_key, menu_level, sort_ord) VALUES
('dashboard',           NULL, 'ITEM', '/dashboard',           'dashboard',                        'features/dashboard/Dashboard',                  'LayoutDashboard', 'nav.dashboard',           0,  100),
('monitoring',          NULL, 'ITEM', '/monitoring',           'monitoring',                       'features/monitoring/MonitoringDashboard',        'Activity',        'nav.monitoring',          0,  200),
('events',              NULL, 'ITEM', '/events',               'surveillance:live-map',            'features/surveillance/LiveMapView',              'Radar',           'nav.realtimeEvent',       0,  300),
('map-control',         NULL, 'ITEM', '/map-control',          'surveillance:map-control',         'features/surveillance/MapControl',               'Map',             'nav.mapControl',          0,  400),
('risk-map',            NULL, 'ITEM', '/risk-map',             'risk-assessment:risk-map',         'features/risk-assessment/RiskMap',               'Layers',          'nav.riskMap',             0,  500),
('enforcement-plan',    NULL, 'ITEM', '/enforcement-plan',     'risk-assessment:enforcement-plan', 'features/risk-assessment/EnforcementPlan',       'Shield',          'nav.enforcementPlan',     0,  600),
('dark-vessel',         NULL, 'ITEM', '/dark-vessel',          'detection:dark-vessel',            'features/detection/DarkVesselDetection',         'EyeOff',          'nav.darkVessel',          0,  700),
('gear-detection',      NULL, 'ITEM', '/gear-detection',       'detection:gear-detection',         'features/detection/GearDetection',               'Anchor',          'nav.gearDetection',       0,  800),
('china-fishing',       NULL, 'ITEM', '/china-fishing',        'detection:china-fishing',          'features/detection/ChinaFishing',                'Ship',            'nav.chinaFishing',        0,  900),
('enforcement-history', NULL, 'ITEM', '/enforcement-history',  'enforcement:enforcement-history',  'features/enforcement/EnforcementHistory',        'FileText',        'nav.enforcementHistory',  0, 1000),
('event-list',          NULL, 'ITEM', '/event-list',           'enforcement:event-list',           'features/enforcement/EventList',                 'List',            'nav.eventList',           0, 1100),
('statistics',          NULL, 'ITEM', '/statistics',           'statistics:statistics',             'features/statistics/Statistics',                  'BarChart3',       'nav.statistics',          0, 1200),
('reports',             NULL, 'ITEM', '/reports',              'statistics:statistics',             'features/statistics/ReportManagement',            'FileText',        'nav.reports',             0, 1300);

-- ─── GROUP: 현장작전 ───────────────────────────────────────────────────────
INSERT INTO kcg.menu_config(menu_cd, parent_menu_cd, menu_type, url_path, rsrc_cd, component_key, icon, label_key, menu_level, sort_ord) VALUES
('field-ops',             NULL,          'GROUP', NULL,                  NULL,                               NULL,                                            'Ship',        'group.fieldOps',          0, 1400),
('field-ops.patrol',      'field-ops',   'ITEM',  '/patrol-route',       'patrol:patrol-route',              'features/patrol/PatrolRoute',                   'Navigation',  'nav.patrolRoute',         1,  100),
('field-ops.fleet',       'field-ops',   'ITEM',  '/fleet-optimization', 'patrol:fleet-optimization',        'features/patrol/FleetOptimization',             'Users',       'nav.fleetOptimization',   1,  200),
('field-ops.alert',       'field-ops',   'ITEM',  '/ai-alert',           'field-ops:ai-alert',               'features/field-ops/AIAlert',                    'Send',        'nav.aiAlert',             1,  300),
('field-ops.mobile',      'field-ops',   'ITEM',  '/mobile-service',     'field-ops:mobile-service',         'features/field-ops/MobileService',              'Smartphone',  'nav.mobileService',       1,  400),
('field-ops.ship',        'field-ops',   'ITEM',  '/ship-agent',         'field-ops:ship-agent',             'features/field-ops/ShipAgent',                  'Monitor',     'nav.shipAgent',           1,  500);

-- ─── GROUP: 모선 워크플로우 ────────────────────────────────────────────────
INSERT INTO kcg.menu_config(menu_cd, parent_menu_cd, menu_type, url_path, rsrc_cd, component_key, icon, label_key, menu_level, sort_ord) VALUES
('parent-inference',           NULL,                'GROUP', NULL,                              NULL,                                               NULL,                                               'GitBranch',   'group.parentInference',   0, 1500),
('parent-inference.review',    'parent-inference',  'ITEM',  '/parent-inference/review',        'parent-inference-workflow:parent-review',           'features/parent-inference/ParentReview',            'CheckSquare', 'nav.parentReview',        1,  100),
('parent-inference.exclusion', 'parent-inference',  'ITEM',  '/parent-inference/exclusion',     'parent-inference-workflow:parent-exclusion',        'features/parent-inference/ParentExclusion',         'Ban',         'nav.parentExclusion',     1,  200),
('parent-inference.label',     'parent-inference',  'ITEM',  '/parent-inference/label-session', 'parent-inference-workflow:label-session',           'features/parent-inference/LabelSession',            'Tag',         'nav.labelSession',        1,  300);

-- ─── GROUP: 관리자 ─────────────────────────────────────────────────────────
INSERT INTO kcg.menu_config(menu_cd, parent_menu_cd, menu_type, url_path, rsrc_cd, component_key, icon, label_key, divider_label, menu_level, sort_ord) VALUES
('admin-group',                NULL,           'GROUP',   NULL,                   NULL,                            NULL,                                              'Settings',       'group.admin',     NULL,          0, 1600),
-- AI 플랫폼
('admin-group.div-ai',         'admin-group',  'DIVIDER', NULL,                   NULL,                            NULL,                                              NULL,             NULL,              'AI 플랫폼',   1,  100),
('admin-group.ai-model',       'admin-group',  'ITEM',    '/ai-model',            'ai-operations:ai-model',        'features/ai-operations/AIModelManagement',         'Brain',          'nav.aiModel',     NULL,          1,  200),
('admin-group.mlops',          'admin-group',  'ITEM',    '/mlops',               'ai-operations:mlops',           'features/ai-operations/MLOpsPage',                 'Cpu',            'nav.mlops',       NULL,          1,  300),
('admin-group.llm-ops',        'admin-group',  'ITEM',    '/llm-ops',             'ai-operations:llm-ops',         'features/ai-operations/LLMOpsPage',                'Brain',          'nav.llmOps',      NULL,          1,  400),
('admin-group.ai-assistant',   'admin-group',  'ITEM',    '/ai-assistant',        'ai-operations:ai-assistant',    'features/ai-operations/AIAssistant',               'MessageSquare',  'nav.aiAssistant', NULL,          1,  500),
-- 시스템 운영
('admin-group.div-sys',        'admin-group',  'DIVIDER', NULL,                   NULL,                            NULL,                                              NULL,             NULL,              '시스템 운영',  1,  600),
('admin-group.system-config',  'admin-group',  'ITEM',    '/system-config',       'admin:system-config',           'features/admin/SystemConfig',                      'Database',       'nav.systemConfig',NULL,          1,  700),
('admin-group.data-hub',       'admin-group',  'ITEM',    '/data-hub',            'admin:system-config',           'features/admin/DataHub',                           'Wifi',           'nav.dataHub',     NULL,          1,  800),
('admin-group.external',       'admin-group',  'ITEM',    '/external-service',    'statistics:external-service',   'features/statistics/ExternalService',              'Globe',          'nav.externalService', NULL,      1,  900),
-- 사용자 관리
('admin-group.div-user',       'admin-group',  'DIVIDER', NULL,                   NULL,                            NULL,                                              NULL,             NULL,              '사용자 관리',  1, 1000),
('admin-group.admin',          'admin-group',  'ITEM',    '/admin',               'admin',                         'features/admin/AdminPanel',                        'Settings',       'nav.admin',       NULL,          1, 1100),
('admin-group.access',         'admin-group',  'ITEM',    '/access-control',      'admin:permission-management',   'features/admin/AccessControl',                     'Fingerprint',    'nav.accessControl', NULL,        1, 1200),
('admin-group.notices',        'admin-group',  'ITEM',    '/notices',             'admin',                         'features/admin/NoticeManagement',                  'Megaphone',      'nav.notices',     NULL,          1, 1300),
-- 감사·보안
('admin-group.div-audit',      'admin-group',  'DIVIDER', NULL,                   NULL,                            NULL,                                              NULL,             NULL,              '감사·보안',    1, 1400),
('admin-group.audit-logs',     'admin-group',  'ITEM',    '/admin/audit-logs',    'admin:audit-logs',              'features/admin/AuditLogs',                         'ScrollText',     'nav.auditLogs',   NULL,          1, 1500),
('admin-group.access-logs',    'admin-group',  'ITEM',    '/admin/access-logs',   'admin:access-logs',             'features/admin/AccessLogs',                        'History',        'nav.accessLogs',  NULL,          1, 1600),
('admin-group.login-history',  'admin-group',  'ITEM',    '/admin/login-history', 'admin:login-history',           'features/admin/LoginHistoryView',                  'KeyRound',       'nav.loginHistory',NULL,          1, 1700);

-- ─── 숨김 라우트 (사이드바 미표시, 라우팅만) ───────────────────────────────
INSERT INTO kcg.menu_config(menu_cd, parent_menu_cd, menu_type, url_path, rsrc_cd, component_key, icon, label_key, menu_level, sort_ord, use_yn) VALUES
('vessel-detail', NULL, 'ITEM', '/vessel/:id', 'vessel:vessel-detail', 'features/vessel/VesselDetail', NULL, NULL, 0, 9999, 'H');
