-- V61: 분급계획(INSTALLMENT_PLAN) 메뉴 및 권한 등록
-- InstallmentController 에서 menu="INSTALLMENT_PLAN" 사용

-- 1. INSTALLMENT_PLAN 메뉴 PAGE 등록 (GRP_RULE 하위)
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, 'INSTALLMENT_PLAN', '분급 계획', 'PAGE', '/rules/installment-plans', 'rule/InstallmentPlanList', 2, 9, 'Y', 'Y'
FROM menu p
WHERE p.menu_code = 'GRP_RULE'
  AND NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = 'INSTALLMENT_PLAN');

-- 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 = 'INSTALLMENT_PLAN'
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 = 'INSTALLMENT_PLAN'
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 = 'INSTALLMENT_PLAN'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;
