-- ============================================================================
-- V003: 초기 역할 + 리소스 트리 시드 + 역할별 권한 매트릭스
-- ============================================================================

-- ----------------------------------------------------------------------------
-- 역할 시드 (5종)
-- ----------------------------------------------------------------------------
INSERT INTO kcg.auth_role(role_cd, role_nm, role_dc, dflt_yn, builtin_yn) VALUES
    ('ADMIN',    '시스템 관리자', '모든 권한 + 사용자/역할/권한 관리', 'N', 'Y'),
    ('OPERATOR', '운영자',       '분석 + 모선 확정/제외/학습 의사결정', 'N', 'Y'),
    ('ANALYST',  '분석가',       '조회 + 분석 (확정 권한 없음)',      'N', 'Y'),
    ('VIEWER',   '조회자',       '읽기 전용',                         'Y', 'Y'),
    ('FIELD',    '현장요원',     '현장 작전 + 알림',                  'N', 'Y');

-- ----------------------------------------------------------------------------
-- Level 0: 좌측 탭 (권한 그룹)
-- ----------------------------------------------------------------------------
INSERT INTO kcg.auth_perm_tree(rsrc_cd, parent_cd, rsrc_nm, rsrc_level, sort_ord, icon) VALUES
    ('dashboard',                  NULL, '대시보드',          0,  10, 'LayoutDashboard'),
    ('monitoring',                 NULL, '실시간 모니터링',   0,  20, 'Activity'),
    ('surveillance',               NULL, '감시',              0,  30, 'Eye'),
    ('detection',                  NULL, '탐지',              0,  40, 'Radar'),
    ('vessel',                     NULL, '선박',              0,  50, 'Ship'),
    ('risk-assessment',            NULL, '위험평가',          0,  60, 'AlertTriangle'),
    ('patrol',                     NULL, '순찰',              0,  70, 'Navigation'),
    ('enforcement',                NULL, '단속',              0,  80, 'Shield'),
    ('field-ops',                  NULL, '현장작전',          0,  90, 'MapPin'),
    ('ai-operations',              NULL, 'AI 운영',           0, 100, 'Bot'),
    ('statistics',                 NULL, '통계',              0, 110, 'BarChart3'),
    ('parent-inference-workflow',  NULL, '모선 워크플로우',   0, 120, 'GitBranch'),
    ('admin',                      NULL, '관리',              0, 999, 'Settings');

-- ----------------------------------------------------------------------------
-- Level 1: 서브탭/패널
-- ----------------------------------------------------------------------------
INSERT INTO kcg.auth_perm_tree(rsrc_cd, parent_cd, rsrc_nm, rsrc_level, sort_ord) VALUES
    -- monitoring
    ('monitoring:alert-list',                       'monitoring',                 '알림 목록',       1, 10),
    ('monitoring:kpi-panel',                        'monitoring',                 'KPI 패널',        1, 20),
    -- surveillance
    ('surveillance:live-map',                       'surveillance',               '실시간 맵',       1, 10),
    ('surveillance:map-control',                    'surveillance',               '해역 관리',       1, 20),
    -- detection
    ('detection:gear-detection',                    'detection',                  '어구탐지',        1, 10),
    ('detection:dark-vessel',                       'detection',                  'Dark Vessel',     1, 20),
    ('detection:china-fishing',                     'detection',                  '중국어선',        1, 30),
    ('detection:gear-identification',               'detection',                  '어구식별',        1, 40),
    -- vessel
    ('vessel:vessel-detail',                        'vessel',                     '선박상세',        1, 10),
    ('vessel:transfer-detection',                   'vessel',                     '전재탐지',        1, 20),
    -- risk-assessment
    ('risk-assessment:risk-map',                    'risk-assessment',            '위험지도',        1, 10),
    ('risk-assessment:enforcement-plan',            'risk-assessment',            '단속계획',        1, 20),
    -- patrol
    ('patrol:patrol-route',                         'patrol',                     '순찰경로',        1, 10),
    ('patrol:fleet-optimization',                   'patrol',                     '선단최적화',      1, 20),
    -- enforcement
    ('enforcement:enforcement-history',             'enforcement',                '단속이력',        1, 10),
    ('enforcement:event-list',                      'enforcement',                '이벤트 목록',     1, 20),
    -- field-ops
    ('field-ops:mobile-service',                    'field-ops',                  '모바일 서비스',   1, 10),
    ('field-ops:ship-agent',                        'field-ops',                  '함정 에이전트',   1, 20),
    ('field-ops:ai-alert',                          'field-ops',                  'AI 경보',         1, 30),
    -- ai-operations
    ('ai-operations:ai-assistant',                  'ai-operations',              'AI 어시스턴트',   1, 10),
    ('ai-operations:ai-model',                      'ai-operations',              'AI 모델',         1, 20),
    ('ai-operations:mlops',                         'ai-operations',              'MLOps',           1, 30),
    -- statistics
    ('statistics:statistics',                       'statistics',                 '통계',            1, 10),
    ('statistics:external-service',                 'statistics',                 '외부 서비스',     1, 20),
    -- parent-inference-workflow ★
    ('parent-inference-workflow:parent-review',     'parent-inference-workflow',  '확정/거부',       1, 10),
    ('parent-inference-workflow:parent-exclusion',  'parent-inference-workflow',  '후보 제외',       1, 20),
    ('parent-inference-workflow:label-session',     'parent-inference-workflow',  '학습 세션',       1, 30),
    ('parent-inference-workflow:exclusion-management','parent-inference-workflow','전역 제외 관리',  1, 40),
    -- admin ★
    ('admin:user-management',                       'admin',                      '사용자 관리',     1, 10),
    ('admin:role-management',                       'admin',                      '역할 관리',       1, 20),
    ('admin:permission-management',                 'admin',                      '권한 관리',       1, 30),
    ('admin:menu-management',                       'admin',                      '메뉴 설정',       1, 40),
    ('admin:audit-logs',                            'admin',                      '감사로그',        1, 50),
    ('admin:access-logs',                           'admin',                      '접근 이력',       1, 60),
    ('admin:login-history',                         'admin',                      '로그인 이력',     1, 70),
    ('admin:system-config',                         'admin',                      '시스템 설정',     1, 80);

-- ----------------------------------------------------------------------------
-- 권한 시드: 헬퍼 - 역할별로 일괄 INSERT
-- ----------------------------------------------------------------------------

-- ADMIN: 모든 리소스에 대해 R/C/U/D/EXPORT 부여
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, op.oper_cd, 'Y'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
CROSS JOIN (VALUES ('READ'), ('CREATE'), ('UPDATE'), ('DELETE'), ('EXPORT')) AS op(oper_cd)
WHERE r.role_cd = 'ADMIN';

-- VIEWER: 모든 view 탭(READ만), admin/parent-inference-workflow는 deny
-- (1) view 가능 Level 0 탭에만 READ 부여
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, 'READ', 'Y'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
WHERE r.role_cd = 'VIEWER'
  AND t.rsrc_level = 0
  AND t.rsrc_cd NOT IN ('admin', 'parent-inference-workflow');

-- (2) admin / parent-inference-workflow는 명시적 deny
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, 'READ', 'N'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
WHERE r.role_cd = 'VIEWER'
  AND t.rsrc_level = 0
  AND t.rsrc_cd IN ('admin', 'parent-inference-workflow');

-- ANALYST: 모든 view + parent-inference-workflow READ만 (확정 권한 없음)
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, 'READ', 'Y'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
WHERE r.role_cd = 'ANALYST'
  AND t.rsrc_level = 0
  AND t.rsrc_cd != 'admin';

INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, 'admin', 'READ', 'N'
FROM kcg.auth_role r WHERE r.role_cd = 'ANALYST';

-- OPERATOR: 모든 view + parent-inference-workflow R/C/U + admin은 거부
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, 'READ', 'Y'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
WHERE r.role_cd = 'OPERATOR'
  AND t.rsrc_level = 0
  AND t.rsrc_cd != 'admin';

-- OPERATOR에 parent-inference-workflow의 자식 리소스에 R/C/U 부여
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, op.oper_cd, 'Y'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
CROSS JOIN (VALUES ('READ'), ('CREATE'), ('UPDATE')) AS op(oper_cd)
WHERE r.role_cd = 'OPERATOR'
  AND t.parent_cd = 'parent-inference-workflow'
  AND t.rsrc_cd != 'parent-inference-workflow:exclusion-management'; -- 전역 제외는 admin만

INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, 'admin', 'READ', 'N'
FROM kcg.auth_role r WHERE r.role_cd = 'OPERATOR';

-- FIELD: field-ops, vessel, monitoring, dashboard READ만
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, 'READ', 'Y'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
WHERE r.role_cd = 'FIELD'
  AND t.rsrc_level = 0
  AND t.rsrc_cd IN ('dashboard', 'monitoring', 'vessel', 'field-ops');

-- 다른 모든 탭 명시적 deny
INSERT INTO kcg.auth_perm(role_sn, rsrc_cd, oper_cd, grant_yn)
SELECT r.role_sn, t.rsrc_cd, 'READ', 'N'
FROM kcg.auth_role r
CROSS JOIN kcg.auth_perm_tree t
WHERE r.role_cd = 'FIELD'
  AND t.rsrc_level = 0
  AND t.rsrc_cd NOT IN ('dashboard', 'monitoring', 'vessel', 'field-ops');

-- ----------------------------------------------------------------------------
-- 초기 admin 계정 시드 (Phase 3에서 BCrypt 해시로 갱신)
-- ----------------------------------------------------------------------------
INSERT INTO kcg.auth_user(user_acnt, user_nm, user_stts_cd, auth_provider, pswd_hash)
VALUES ('admin', '시스템 관리자', 'ACTIVE', 'PASSWORD', '$2a$10$placeholder.will.be.set.in.phase3');

INSERT INTO kcg.auth_user_role(user_id, role_sn)
SELECT u.user_id, r.role_sn
FROM kcg.auth_user u, kcg.auth_role r
WHERE u.user_acnt = 'admin' AND r.role_cd = 'ADMIN';
