-- V60: 수수료명세서(STATEMENT) 메뉴 및 권한 등록
-- CommissionStatementController 에서 menu="STATEMENT" 사용

-- 1. STATEMENT 메뉴 PAGE 등록 (GRP_SETTLE 하위)
INSERT INTO menu (parent_menu_id, menu_code, menu_name, menu_type, menu_path, component_path, menu_level, sort_order, is_visible, is_active)
SELECT p.menu_id, 'STATEMENT', '수수료 명세서', 'PAGE', '/statements', 'settle/CommissionStatement', 2, 70, 'Y', 'Y'
FROM menu p
WHERE p.menu_code = 'GRP_SETTLE'
  AND NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = 'STATEMENT');

-- 2. 권한 항목 등록
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),
    ('UPDATE', '수정', 30)
) AS p(code, name, sort)
WHERE m.menu_code = 'STATEMENT'
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- 3. 역할별 권한 부여
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 = 'STATEMENT'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

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