-- V113: 환수자료관리 메뉴/권한 등록 (P10 §5)
--       신규 테이블 없음 — 기존 chargeback 테이블 재사용.
--       GRP_SETTLE 하위 PAGE: CHARGEBACK_DATA (sort_order 110, HQ_SETTLE=100 다음)
--       권한: READ / CREATE / EXPORT
--       역할: SUPER_ADMIN·ADMIN 전체, MANAGER READ 만
--       모든 INSERT 멱등 (ON CONFLICT DO NOTHING / WHERE NOT EXISTS)

-- ============================================================
-- 1. 메뉴 INSERT: CHARGEBACK_DATA (GRP_SETTLE 하위 PAGE)
-- ============================================================

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
    ('CHARGEBACK_DATA', '환수자료관리', '/settle/chargeback-data', 'settle/ChargebackData', 110)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_SETTLE'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 2. 메뉴 권한 항목 등록 (READ / CREATE / 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),
    ('CREATE', '등록', 20),
    ('EXPORT', '엑셀', 60)
) AS p(code, name, sort)
WHERE m.menu_code = 'CHARGEBACK_DATA'
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 3. 역할별 권한 부여
-- ============================================================

-- SUPER_ADMIN / ADMIN — 전체 권한 (READ / CREATE / 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')
  AND m.menu_code = 'CHARGEBACK_DATA'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- MANAGER — READ 만
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 = 'MANAGER'
  AND mp.perm_code = 'READ'
  AND m.menu_code = 'CHARGEBACK_DATA'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;
