-- V54: P4 도메인 메뉴 일괄 등록 (V40~V53 대응)
--
-- 신규 부모 그룹: GRP_COMMISSION "수수료 마스터" (P4-A 5개 자식)
-- 기존 GRP_ORG 아래: 위촉계약/자격관리/보수교육
-- 기존 GRP_PRD 아래: 계약변경/민원관리  (GRP_CONTRACT_OP 대신 GRP_PRD 활용)
-- 기존 GRP_SYSTEM 아래: 결재/공지/첨부/출금

-- ============================================================
-- 1. GRP_COMMISSION 부모 그룹 메뉴 신설
-- ============================================================

INSERT INTO menu (parent_menu_id, menu_code, menu_name, menu_type, menu_path, menu_icon, menu_level, sort_order, is_visible, is_active, description)
VALUES (NULL, 'GRP_COMMISSION', '수수료 마스터', 'DIRECTORY', NULL, 'dollar', 1, 45, 'Y', 'Y', '수수료 종류별 원장 · 룰 관리')
ON CONFLICT (menu_code) DO NOTHING;

-- ============================================================
-- 2. GRP_COMMISSION 하위 PAGE 5개 (P4-A)
-- ============================================================

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
    ('COMM_TYPE',       '수수료 종류 코드',   '/commission/type',       'commission/CommType',        10),
    ('COMM_MASTER',     '수수료 통합 원장',   '/commission/master',     'commission/CommMaster',      20),
    ('COLLECT_COMM',    '수금수수료',         '/commission/collection', 'commission/CollectComm',     30),
    ('RENEWAL_COMM',    '갱신수수료',         '/commission/renewal',    'commission/RenewalComm',     40),
    ('REINSTATE_COMM',  '부활수수료',         '/commission/reinstate',  'commission/ReinstateComm',   50),
    ('PERSIST_BONUS',   '유지보수수당',       '/commission/persist',    'commission/PersistBonus',    60),
    ('OVERRIDE_LEDGER', '오버라이드 원장',    '/commission/override',   'commission/OverrideLedger',  70)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_COMMISSION'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 3. GRP_ORG 하위 PAGE 3개 (P4-B 설계사 라이프사이클)
-- ============================================================

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
    ('AGENT_CONTRACT', '위촉계약',   '/org/agent-contract', 'org/AgentContract', 30),
    ('AGENT_LICENSE',  '자격 관리',  '/org/agent-license',  'org/AgentLicense',  40),
    ('AGENT_TRAINING', '보수교육',   '/org/agent-training', 'org/AgentTraining', 50)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_ORG'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 4. GRP_PRD 하위 PAGE 2개 (계약변경 / 민원관리)
-- ============================================================

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
    ('ENDORSE',   '계약 변경', '/contract/endorsement', 'contract/Endorsement', 40),
    ('COMPLAINT', '민원 관리', '/contract/complaint',   'contract/Complaint',   50)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_PRD'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 5. GRP_SYSTEM 하위 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
    ('APPROVAL',   '결재 관리',   '/system/approval',    'system/Approval',   70),
    ('NOTICE',     '공지사항',    '/system/notice',      'system/Notice',     80),
    ('ATTACHMENT', '첨부파일',    '/system/attachment',  'system/Attachment', 90),
    ('WITHDRAW',   '출금 신청',   '/system/withdraw',    'system/Withdraw',   95)
) AS x(code, name, path, cmpt, sort)
ON p.menu_code = 'GRP_SYSTEM'
WHERE NOT EXISTS (SELECT 1 FROM menu WHERE menu_code = x.code);

-- ============================================================
-- 6. GRP_COMMISSION 에 READ 권한 등록 (대메뉴 expand 용)
-- ============================================================

INSERT INTO menu_permission (menu_id, perm_code, perm_name, sort_order)
SELECT menu_id, 'READ', '조회', 1 FROM menu WHERE menu_code = 'GRP_COMMISSION'
ON CONFLICT (menu_id, perm_code) DO NOTHING;

INSERT INTO role_menu_permission (role_id, menu_id, perm_code, is_granted)
SELECT r.role_id, m.menu_id, 'READ', 'Y'
FROM role r CROSS JOIN menu m
WHERE r.role_code IN ('SUPER_ADMIN','ADMIN','MANAGER','AGENT')
  AND m.menu_code = 'GRP_COMMISSION'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 7. 전체 신규 PAGE 메뉴에 권한 항목 등록
--    수수료 도메인: READ/CREATE/UPDATE/DELETE/EXPORT
--    관리 도메인(결재/공지/출금): READ/CREATE/UPDATE/APPROVE
--    조회성(첨부): READ/CREATE/DELETE
-- ============================================================

-- 수수료 + 설계사 라이프사이클 + 계약변경/민원: READ/CREATE/UPDATE/DELETE/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),
    ('UPDATE', '수정', 30),
    ('DELETE', '삭제', 40),
    ('EXPORT', '엑셀', 60)
) AS p(code, name, sort)
WHERE m.menu_code IN (
    'COMM_TYPE','COMM_MASTER','COLLECT_COMM','RENEWAL_COMM',
    'REINSTATE_COMM','PERSIST_BONUS','OVERRIDE_LEDGER',
    'AGENT_CONTRACT','AGENT_LICENSE','AGENT_TRAINING',
    'ENDORSE','COMPLAINT'
)
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- 결재/공지/출금: READ/CREATE/UPDATE/APPROVE
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),
    ('APPROVE', '결재', 50)
) AS p(code, name, sort)
WHERE m.menu_code IN ('APPROVAL','NOTICE','WITHDRAW')
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- 첨부파일: READ/CREATE/DELETE
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),
    ('DELETE', '삭제', 40)
) AS p(code, name, sort)
WHERE m.menu_code = 'ATTACHMENT'
ON CONFLICT (menu_id, perm_code) DO NOTHING;

-- ============================================================
-- 8. 역할별 권한 부여
--    SUPER_ADMIN / ADMIN: 전체 부여
--    MANAGER: READ + CREATE + UPDATE + APPROVE (DELETE 제외)
--    AGENT: 본인 관련 READ 만 (COMM_MASTER/AGENT_CONTRACT/AGENT_LICENSE/AGENT_TRAINING/NOTICE/WITHDRAW)
-- ============================================================

-- SUPER_ADMIN / ADMIN — 모든 신규 메뉴 전체 권한
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 IN (
      'COMM_TYPE','COMM_MASTER','COLLECT_COMM','RENEWAL_COMM',
      'REINSTATE_COMM','PERSIST_BONUS','OVERRIDE_LEDGER',
      'AGENT_CONTRACT','AGENT_LICENSE','AGENT_TRAINING',
      'ENDORSE','COMPLAINT',
      'APPROVAL','NOTICE','ATTACHMENT','WITHDRAW'
  )
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- MANAGER — READ/CREATE/UPDATE/APPROVE (DELETE 제외)
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 IN ('READ','CREATE','UPDATE','APPROVE','EXPORT')
  AND m.menu_code IN (
      'COMM_TYPE','COMM_MASTER','COLLECT_COMM','RENEWAL_COMM',
      'REINSTATE_COMM','PERSIST_BONUS','OVERRIDE_LEDGER',
      'AGENT_CONTRACT','AGENT_LICENSE','AGENT_TRAINING',
      'ENDORSE','COMPLAINT',
      'APPROVAL','NOTICE','ATTACHMENT','WITHDRAW'
  )
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- 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 = 'AGENT'
  AND mp.perm_code = 'READ'
  AND m.menu_code IN (
      'COMM_MASTER','AGENT_CONTRACT','AGENT_LICENSE','AGENT_TRAINING',
      'NOTICE','WITHDRAW'
  )
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;
