-- V39: KPI 대시보드 메뉴 4개 추가
-- 부모 그룹: GRP_KPI (신규) — REPORT 그룹과 동일 레벨
-- 화면: KPI_MONTHLY / KPI_ORG / KPI_RETENTION / KPI_CUMULATIVE

-- ============================================================
-- 1. KPI 부모 그룹 메뉴 삽입
-- ============================================================

INSERT INTO menu (parent_menu_id, menu_code, menu_name, menu_type, menu_path, component_path, menu_level, sort_order)
VALUES (NULL, 'GRP_KPI', 'KPI 대시보드', 'GROUP', '/kpi', NULL, 1, 80)
ON CONFLICT (menu_code) DO NOTHING;

-- ============================================================
-- 2. KPI 하위 PAGE 메뉴 4개 삽입
-- ============================================================

INSERT INTO menu (parent_menu_id, menu_code, menu_name, menu_type, menu_path, component_path, menu_level, sort_order)
SELECT p.menu_id, x.code, x.name, 'PAGE', x.path, x.cmpt, 2, x.sort
FROM menu p
JOIN (VALUES
    ('KPI_MONTHLY',    '월별 정산 요약', '/kpi/monthly',    'kpi/KpiMonthlySummary', 10),
    ('KPI_ORG',        '조직별 요약',    '/kpi/org',        'kpi/KpiOrgSummary',     20),
    ('KPI_RETENTION',  '유지율 현황',    '/kpi/retention',  'kpi/KpiRetention',      30),
    ('KPI_CUMULATIVE', '누계 현황',      '/kpi/cumulative', 'kpi/KpiCumulative',     40)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_KPI'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 3. 권한 항목 (READ + EXPORT) 등록
-- ============================================================

INSERT INTO menu_permission (menu_id, perm_code, perm_name, sort_order)
SELECT m.menu_id, p.code, p.name, p.sort
FROM menu m
CROSS JOIN (VALUES
    ('READ',   '조회', 10),
    ('EXPORT', '엑셀', 60)
) AS p(code, name, sort)
WHERE m.menu_code IN (
    'KPI_MONTHLY', 'KPI_ORG', 'KPI_RETENTION', 'KPI_CUMULATIVE'
)
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 4. SUPER_ADMIN / ADMIN / MANAGER 에게 READ + EXPORT 부여
-- ============================================================

INSERT INTO role_menu_permission (role_id, menu_id, perm_code, is_granted)
SELECT r.role_id, mp.menu_id, mp.perm_code, 'Y'
FROM role r
CROSS JOIN menu_permission mp
JOIN menu m ON m.menu_id = mp.menu_id
WHERE r.role_code IN ('SUPER_ADMIN', 'ADMIN', 'MANAGER')
  AND m.menu_code IN (
      'KPI_MONTHLY', 'KPI_ORG', 'KPI_RETENTION', 'KPI_CUMULATIVE'
  )
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;
