-- V16: 관리자 계정 + 메뉴 상세 + 권한 매트릭스 초기화
-- admin 계정 비밀번호: admin1234!  (BCrypt $2b$10)

-- 0. PAYMENT 메뉴는 V12에서 level 1 directory 로 생성되었으나
--    PaymentController 에서 menu="PAYMENT" 로 직접 권한 체크하므로 PAGE 로 변경.
UPDATE menu SET menu_type = 'PAGE',
                menu_path = '/payments',
                component_path = 'settle/PaymentList'
WHERE menu_code = 'PAYMENT';

-- 1. 자식 메뉴 (V10에서 정의된 menu_code 와 컨트롤러 @RequirePermission 매칭)
WITH parent AS (
    SELECT menu_id, menu_code FROM menu WHERE menu_level = 1
)
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 parent p
JOIN (VALUES
    -- 조직
    ('ORG',      'ORG_TREE',         '조직 트리',         '/org/tree',         'org/OrgTree',          10),
    ('ORG',      'ORG_AGENT',        '설계사 관리',       '/org/agents',       'org/AgentList',        20),
    -- 계약
    ('CONTRACT', 'CONTRACT_LIST',    '계약 목록',         '/contracts',        'product/ContractList', 10),
    ('CONTRACT', 'COMPANY',          '보험사 관리',       '/companies',        'product/CompanyList',  20),
    ('CONTRACT', 'PRODUCT',          '상품 관리',         '/products',         'product/ProductList',  30),
    -- 수수료 규정
    ('RULE',     'RULE_COMMISSION',  '보험사 수수료율',   '/rules/commission', 'rule/CommissionRate',  10),
    ('RULE',     'RULE_PAYOUT',      '지급율 관리',       '/rules/payout',     'rule/PayoutRule',      20),
    ('RULE',     'RULE_OVERRIDE',    '오버라이드 규정',   '/rules/override',   'rule/OverrideRule',    30),
    ('RULE',     'RULE_CHARGEBACK',  '환수 규정',         '/rules/chargeback', 'rule/ChargebackRule',  40),
    ('RULE',     'RULE_EXCEPTION',   '예외코드 관리',     '/rules/exceptions', 'rule/ExceptionCode',   50),
    -- 데이터 수신
    ('RECEIVE',  'RECEIVE_MAPPING',  '매핑 관리',         '/receive/mapping',  'receive/Mapping',      10),
    ('RECEIVE',  'RECEIVE_DATA',     '수신 데이터',       '/receive/data',     'receive/RawData',      20),
    -- 원장
    ('LEDGER',   'LEDGER_RECRUIT',   '모집수수료원장',    '/ledger/recruit',   'ledger/RecruitLedger', 10),
    ('LEDGER',   'LEDGER_MAINTAIN',  '유지수수료원장',    '/ledger/maintain',  'ledger/MaintainLedger',20),
    ('LEDGER',   'LEDGER_EXCEPTION', '예외금액원장',      '/ledger/exception', 'ledger/ExceptionLedger',30),
    -- 정산/지급
    ('SETTLE',   'SETTLE_LIST',      '정산 결과',         '/settle',           'settle/SettleList',    10),
    ('SETTLE',   'BATCH_RUN',        '정산 배치',         '/settle/batch',     'settle/BatchRun',      20),
    -- 시스템
    ('SYSTEM',   'SYSTEM_USER',      '사용자 관리',       '/system/users',     'system/UserList',      10),
    ('SYSTEM',   'SYSTEM_ROLE',      '역할 관리',         '/system/roles',     'system/RoleList',      20),
    ('SYSTEM',   'SYSTEM_MENU',      '메뉴 관리',         '/system/menus',     'system/MenuTree',      30),
    ('SYSTEM',   'SYSTEM_CODE',      '공통코드 관리',     '/system/codes',     'system/CodeList',      40),
    ('SYSTEM',   'SYSTEM_CONFIG',    '시스템 설정',       '/system/config',    'system/ConfigList',    50),
    ('SYSTEM',   'SYSTEM_LOG',       '시스템 로그',       '/system/logs',      'system/LogList',       60)
) AS x(parent_code, code, name, path, cmpt, sort)
ON p.menu_code = x.parent_code;

-- 2. 메뉴별 권한 항목 (READ/CREATE/UPDATE/DELETE/APPROVE/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),
    ('APPROVE', '승인',    50),
    ('EXPORT',  '엑셀',    60)
) AS p(code, name, sort)
WHERE m.menu_type = 'PAGE';

-- 3. SUPER_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
WHERE r.role_code = 'SUPER_ADMIN'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- 4. 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
JOIN menu pm ON pm.menu_id = m.parent_menu_id
WHERE r.role_code = 'ADMIN' AND pm.menu_code <> 'SYSTEM'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- 5. MANAGER 에는 조회/등록/수정/엑셀만 (승인/삭제 제외, 시스템관리 제외)
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
JOIN menu pm ON pm.menu_id = m.parent_menu_id
WHERE r.role_code = 'MANAGER'
  AND pm.menu_code <> 'SYSTEM'
  AND mp.perm_code IN ('READ','CREATE','UPDATE','EXPORT')
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- 6. AGENT 에는 본인 정보 조회 권한만 (LEDGER/SETTLE READ)
INSERT INTO role_menu_permission (role_id, menu_id, perm_code, is_granted)
SELECT r.role_id, mp.menu_id, 'READ', '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 m.menu_code IN ('LEDGER_RECRUIT','LEDGER_MAINTAIN','SETTLE_LIST')
  AND mp.perm_code = 'READ'
ON CONFLICT (role_id, menu_id, perm_code) DO NOTHING;

-- 7. admin 사용자 (BCrypt: admin1234!)
INSERT INTO users (login_id, password, user_name, email, status, fail_count, pwd_changed_at, created_at)
VALUES ('admin', '$2b$10$NClaIICfNMTGWyto9X6gV.yrnYEyiQeakgirWfxRJh.vYfDtubKdu',
        '시스템 관리자', 'admin@example.com', 'ACTIVE', 0, NOW(), NOW())
ON CONFLICT (login_id) DO NOTHING;

-- 8. admin → SUPER_ADMIN 매핑
INSERT INTO user_role (user_id, role_id)
SELECT u.user_id, r.role_id
FROM users u, role r
WHERE u.login_id = 'admin' AND r.role_code = 'SUPER_ADMIN'
ON CONFLICT (user_id, role_id) DO NOTHING;
