-- V62: 시책지급/보험사대사/해촉정산 메뉴 및 권한 등록
-- IncentivePaymentController  -> menu="INCENTIVE_PAY"
-- CarrierReconciliationOutController -> menu="RECON_OUT"
-- TerminationSettlementController    -> menu="TERM_SETTLE"

-- ============================================================
-- 1. GRP_SETTLE 하위 PAGE 3개 등록
-- ============================================================
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, x.code, x.name, 'PAGE', x.path, x.cmpt, 2, x.sort, 'Y', 'Y'
FROM menu p
JOIN (VALUES
    ('INCENTIVE_PAY', '시책 지급',   '/settle/incentive-payments',   'settle/IncentivePayment',   65),
    ('RECON_OUT',     '보험사 대사', '/settle/carrier-reconciliation','settle/CarrierReconOut',     70),
    ('TERM_SETTLE',   '해촉 정산',   '/settle/termination',           'settle/TerminationSettle',  80)
) 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/UPDATE
-- ============================================================
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 IN ('INCENTIVE_PAY','RECON_OUT','TERM_SETTLE')
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- 시책지급에 APPROVE 권한 추가
INSERT INTO menu_permission (menu_id, perm_code, perm_name, sort_order)
SELECT m.menu_id, 'APPROVE', '승인', 50
FROM menu m
WHERE m.menu_code = 'INCENTIVE_PAY'
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 3. 역할별 권한 부여 — SUPER_ADMIN/ADMIN/MANAGER: 전체, AGENT: 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 IN ('SUPER_ADMIN', 'ADMIN', 'MANAGER')
  AND m.menu_code IN ('INCENTIVE_PAY','RECON_OUT','TERM_SETTLE')
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 IN ('INCENTIVE_PAY','RECON_OUT','TERM_SETTLE')
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;
