-- ============================================================================
-- V021: auth_perm_tree를 메뉴 SSOT로 확장 + menu_config 테이블 폐기
-- 메뉴·권한·감사가 동일 레코드를 참조하여 완전 동기화
-- ============================================================================

-- ──────────────────────────────────────────────────────────────────
-- 1. auth_perm_tree에 메뉴 컬럼 추가
-- ──────────────────────────────────────────────────────────────────
ALTER TABLE kcg.auth_perm_tree ADD COLUMN url_path      VARCHAR(200);
ALTER TABLE kcg.auth_perm_tree ADD COLUMN label_key     VARCHAR(100);
ALTER TABLE kcg.auth_perm_tree ADD COLUMN component_key VARCHAR(150);
ALTER TABLE kcg.auth_perm_tree ADD COLUMN nav_group     VARCHAR(100);   -- 소속 메뉴 그룹 (NULL=최상위)
ALTER TABLE kcg.auth_perm_tree ADD COLUMN nav_sub_group VARCHAR(100);   -- 디바이더 라벨 (admin 서브그룹)
ALTER TABLE kcg.auth_perm_tree ADD COLUMN nav_sort      INT NOT NULL DEFAULT 0;  -- 메뉴 정렬 (0=미표시)

-- ──────────────────────────────────────────────────────────────────
-- 2. 공유 리소스 분리 — 1메뉴=1노드 보장
-- ──────────────────────────────────────────────────────────────────
INSERT INTO kcg.auth_perm_tree(rsrc_cd, parent_cd, rsrc_nm, rsrc_level, sort_ord)
VALUES ('statistics:reports', 'statistics', '보고서 관리', 1, 30)
ON CONFLICT (rsrc_cd) DO NOTHING;

INSERT INTO kcg.auth_perm_tree(rsrc_cd, parent_cd, rsrc_nm, rsrc_level, sort_ord)
VALUES ('admin:data-hub', 'admin', '데이터 허브', 1, 85)
ON CONFLICT (rsrc_cd) DO NOTHING;

INSERT INTO kcg.auth_perm_tree(rsrc_cd, parent_cd, rsrc_nm, rsrc_level, sort_ord)
VALUES ('admin:notices', 'admin', '공지사항', 1, 45)
ON CONFLICT (rsrc_cd) DO NOTHING;

-- 신규 노드에 ADMIN 전체 권한 부여
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, n.rsrc_cd, op.oper_cd, 'Y'
FROM kcg.auth_role r
CROSS JOIN (VALUES ('statistics:reports'), ('admin:data-hub'), ('admin:notices')) AS n(rsrc_cd)
CROSS JOIN (VALUES ('READ'), ('CREATE'), ('UPDATE'), ('DELETE'), ('EXPORT')) AS op(oper_cd)
WHERE r.role_cd = 'ADMIN'
ON CONFLICT (role_sn, rsrc_cd, oper_cd) DO NOTHING;

-- 기존 역할에도 READ 부여 (statistics:reports → VIEWER 이상, admin:* → ADMIN 전용)
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, 'statistics:reports', 'READ', 'Y'
FROM kcg.auth_role r WHERE r.role_cd IN ('VIEWER', 'ANALYST', 'OPERATOR', 'FIELD')
ON CONFLICT (role_sn, rsrc_cd, oper_cd) DO NOTHING;

-- ──────────────────────────────────────────────────────────────────
-- 3. 메뉴 데이터 채우기 — 최상위 ITEM (13개)
-- ──────────────────────────────────────────────────────────────────
UPDATE kcg.auth_perm_tree SET url_path='/dashboard',          label_key='nav.dashboard',          component_key='features/dashboard/Dashboard',              nav_sort=100  WHERE rsrc_cd='dashboard';
UPDATE kcg.auth_perm_tree SET url_path='/monitoring',         label_key='nav.monitoring',         component_key='features/monitoring/MonitoringDashboard',   nav_sort=200  WHERE rsrc_cd='monitoring';
UPDATE kcg.auth_perm_tree SET url_path='/events',             label_key='nav.realtimeEvent',      component_key='features/surveillance/LiveMapView',         nav_sort=300  WHERE rsrc_cd='surveillance:live-map';
UPDATE kcg.auth_perm_tree SET url_path='/map-control',        label_key='nav.mapControl',         component_key='features/surveillance/MapControl',          nav_sort=400  WHERE rsrc_cd='surveillance:map-control';
UPDATE kcg.auth_perm_tree SET url_path='/risk-map',           label_key='nav.riskMap',            component_key='features/risk-assessment/RiskMap',          nav_sort=500  WHERE rsrc_cd='risk-assessment:risk-map';
UPDATE kcg.auth_perm_tree SET url_path='/enforcement-plan',   label_key='nav.enforcementPlan',    component_key='features/risk-assessment/EnforcementPlan',  nav_sort=600  WHERE rsrc_cd='risk-assessment:enforcement-plan';
UPDATE kcg.auth_perm_tree SET url_path='/dark-vessel',        label_key='nav.darkVessel',         component_key='features/detection/DarkVesselDetection',    nav_sort=700  WHERE rsrc_cd='detection:dark-vessel';
UPDATE kcg.auth_perm_tree SET url_path='/gear-detection',     label_key='nav.gearDetection',      component_key='features/detection/GearDetection',          nav_sort=800  WHERE rsrc_cd='detection:gear-detection';
UPDATE kcg.auth_perm_tree SET url_path='/china-fishing',      label_key='nav.chinaFishing',       component_key='features/detection/ChinaFishing',           nav_sort=900  WHERE rsrc_cd='detection:china-fishing';
UPDATE kcg.auth_perm_tree SET url_path='/enforcement-history',label_key='nav.enforcementHistory', component_key='features/enforcement/EnforcementHistory',   nav_sort=1000 WHERE rsrc_cd='enforcement:enforcement-history';
UPDATE kcg.auth_perm_tree SET url_path='/event-list',         label_key='nav.eventList',          component_key='features/enforcement/EventList',            nav_sort=1100 WHERE rsrc_cd='enforcement:event-list';
UPDATE kcg.auth_perm_tree SET url_path='/statistics',         label_key='nav.statistics',         component_key='features/statistics/Statistics',             nav_sort=1200 WHERE rsrc_cd='statistics:statistics';
UPDATE kcg.auth_perm_tree SET url_path='/reports',            label_key='nav.reports',            component_key='features/statistics/ReportManagement',      nav_sort=1300 WHERE rsrc_cd='statistics:reports';

-- ──────────────────────────────────────────────────────────────────
-- 4. 그룹 헤더 (Level 0 노드에 label_key + nav_sort)
-- ──────────────────────────────────────────────────────────────────
UPDATE kcg.auth_perm_tree SET label_key='group.fieldOps',          nav_sort=1400 WHERE rsrc_cd='field-ops';
UPDATE kcg.auth_perm_tree SET label_key='group.parentInference',   nav_sort=1500 WHERE rsrc_cd='parent-inference-workflow';
UPDATE kcg.auth_perm_tree SET label_key='group.admin',             nav_sort=1600 WHERE rsrc_cd='admin';

-- ──────────────────────────────────────────────────────────────────
-- 5. 그룹 자식 — field-ops
-- ──────────────────────────────────────────────────────────────────
UPDATE kcg.auth_perm_tree SET url_path='/patrol-route',       label_key='nav.patrolRoute',       component_key='features/patrol/PatrolRoute',       nav_group='field-ops', nav_sort=100 WHERE rsrc_cd='patrol:patrol-route';
UPDATE kcg.auth_perm_tree SET url_path='/fleet-optimization', label_key='nav.fleetOptimization', component_key='features/patrol/FleetOptimization', nav_group='field-ops', nav_sort=200 WHERE rsrc_cd='patrol:fleet-optimization';
UPDATE kcg.auth_perm_tree SET url_path='/ai-alert',           label_key='nav.aiAlert',           component_key='features/field-ops/AIAlert',        nav_group='field-ops', nav_sort=300 WHERE rsrc_cd='field-ops:ai-alert';
UPDATE kcg.auth_perm_tree SET url_path='/mobile-service',     label_key='nav.mobileService',     component_key='features/field-ops/MobileService',  nav_group='field-ops', nav_sort=400 WHERE rsrc_cd='field-ops:mobile-service';
UPDATE kcg.auth_perm_tree SET url_path='/ship-agent',         label_key='nav.shipAgent',         component_key='features/field-ops/ShipAgent',      nav_group='field-ops', nav_sort=500 WHERE rsrc_cd='field-ops:ship-agent';

-- ──────────────────────────────────────────────────────────────────
-- 6. 그룹 자식 — parent-inference
-- ──────────────────────────────────────────────────────────────────
UPDATE kcg.auth_perm_tree SET url_path='/parent-inference/review',        label_key='nav.parentReview',    component_key='features/parent-inference/ParentReview',    nav_group='parent-inference-workflow', nav_sort=100 WHERE rsrc_cd='parent-inference-workflow:parent-review';
UPDATE kcg.auth_perm_tree SET url_path='/parent-inference/exclusion',     label_key='nav.parentExclusion', component_key='features/parent-inference/ParentExclusion', nav_group='parent-inference-workflow', nav_sort=200 WHERE rsrc_cd='parent-inference-workflow:parent-exclusion';
UPDATE kcg.auth_perm_tree SET url_path='/parent-inference/label-session', label_key='nav.labelSession',    component_key='features/parent-inference/LabelSession',    nav_group='parent-inference-workflow', nav_sort=300 WHERE rsrc_cd='parent-inference-workflow:label-session';

-- ──────────────────────────────────────────────────────────────────
-- 7. 그룹 자식 — admin (서브그룹 포함)
-- ──────────────────────────────────────────────────────────────────
-- AI 플랫폼
UPDATE kcg.auth_perm_tree SET url_path='/ai-model',       label_key='nav.aiModel',       component_key='features/ai-operations/AIModelManagement', nav_group='admin', nav_sub_group='AI 플랫폼',   nav_sort=200  WHERE rsrc_cd='ai-operations:ai-model';
UPDATE kcg.auth_perm_tree SET url_path='/mlops',           label_key='nav.mlops',         component_key='features/ai-operations/MLOpsPage',         nav_group='admin', nav_sub_group='AI 플랫폼',   nav_sort=300  WHERE rsrc_cd='ai-operations:mlops';
UPDATE kcg.auth_perm_tree SET url_path='/llm-ops',         label_key='nav.llmOps',        component_key='features/ai-operations/LLMOpsPage',        nav_group='admin', nav_sub_group='AI 플랫폼',   nav_sort=400  WHERE rsrc_cd='ai-operations:llm-ops';
UPDATE kcg.auth_perm_tree SET url_path='/ai-assistant',    label_key='nav.aiAssistant',   component_key='features/ai-operations/AIAssistant',       nav_group='admin', nav_sub_group='AI 플랫폼',   nav_sort=500  WHERE rsrc_cd='ai-operations:ai-assistant';
-- 시스템 운영
UPDATE kcg.auth_perm_tree SET url_path='/system-config',   label_key='nav.systemConfig',  component_key='features/admin/SystemConfig',               nav_group='admin', nav_sub_group='시스템 운영', nav_sort=700  WHERE rsrc_cd='admin:system-config';
UPDATE kcg.auth_perm_tree SET url_path='/data-hub',        label_key='nav.dataHub',       component_key='features/admin/DataHub',                    nav_group='admin', nav_sub_group='시스템 운영', nav_sort=800  WHERE rsrc_cd='admin:data-hub';
UPDATE kcg.auth_perm_tree SET url_path='/external-service',label_key='nav.externalService',component_key='features/statistics/ExternalService',      nav_group='admin', nav_sub_group='시스템 운영', nav_sort=900  WHERE rsrc_cd='statistics:external-service';
-- 사용자 관리
UPDATE kcg.auth_perm_tree SET url_path='/admin',           label_key='nav.admin',         component_key='features/admin/AdminPanel',                 nav_group='admin', nav_sub_group='사용자 관리', nav_sort=1100 WHERE rsrc_cd='admin:user-management';
UPDATE kcg.auth_perm_tree SET url_path='/access-control',  label_key='nav.accessControl', component_key='features/admin/AccessControl',               nav_group='admin', nav_sub_group='사용자 관리', nav_sort=1200 WHERE rsrc_cd='admin:permission-management';
UPDATE kcg.auth_perm_tree SET url_path='/notices',         label_key='nav.notices',       component_key='features/admin/NoticeManagement',            nav_group='admin', nav_sub_group='사용자 관리', nav_sort=1300 WHERE rsrc_cd='admin:notices';
-- 감사·보안
UPDATE kcg.auth_perm_tree SET url_path='/admin/audit-logs',   label_key='nav.auditLogs',    component_key='features/admin/AuditLogs',        nav_group='admin', nav_sub_group='감사·보안', nav_sort=1500 WHERE rsrc_cd='admin:audit-logs';
UPDATE kcg.auth_perm_tree SET url_path='/admin/access-logs',  label_key='nav.accessLogs',   component_key='features/admin/AccessLogs',       nav_group='admin', nav_sub_group='감사·보안', nav_sort=1600 WHERE rsrc_cd='admin:access-logs';
UPDATE kcg.auth_perm_tree SET url_path='/admin/login-history',label_key='nav.loginHistory',  component_key='features/admin/LoginHistoryView', nav_group='admin', nav_sub_group='감사·보안', nav_sort=1700 WHERE rsrc_cd='admin:login-history';

-- ──────────────────────────────────────────────────────────────────
-- 8. 숨김 라우트 (라우팅만, 사이드바 미표시)
-- ──────────────────────────────────────────────────────────────────
UPDATE kcg.auth_perm_tree SET url_path='/vessel/:id', component_key='features/vessel/VesselDetail' WHERE rsrc_cd='vessel:vessel-detail';

-- ──────────────────────────────────────────────────────────────────
-- 9. menu_config 테이블 폐기
-- ──────────────────────────────────────────────────────────────────
DROP TABLE IF EXISTS kcg.menu_config;
