-- ============================================================
-- V008: code_master (계층형 트리 코드 테이블 + 시드)
-- auth_perm_tree와 동일한 self-referencing 패턴
-- ============================================================

CREATE TABLE kcg.code_master (
    code_id     VARCHAR(100) PRIMARY KEY,
    parent_id   VARCHAR(100) REFERENCES kcg.code_master(code_id),
    group_code  VARCHAR(50)  NOT NULL,       -- 루트 그룹 (빠른 필터용 비정규화)
    code        VARCHAR(50)  NOT NULL,       -- 이 레벨의 코드값
    depth       INT          NOT NULL DEFAULT 0,
    name_ko     VARCHAR(100) NOT NULL,
    name_en     VARCHAR(100),
    sort_order  INT          DEFAULT 0,
    color_hex   VARCHAR(10),
    icon        VARCHAR(30),
    metadata    JSONB,
    is_active   BOOLEAN      DEFAULT true,
    created_at  TIMESTAMPTZ  DEFAULT now()
);

CREATE INDEX idx_code_group  ON kcg.code_master(group_code, depth);
CREATE INDEX idx_code_parent ON kcg.code_master(parent_id);

-- ============================================================
-- 위반 유형 (VIOLATION_TYPE)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('VIOLATION_TYPE',                    NULL,              'VIOLATION_TYPE', 'VIOLATION_TYPE',  0, '위반 유형',     'Violation Type',    10, NULL),
('VIOLATION_TYPE:EEZ_VIOLATION',      'VIOLATION_TYPE',  'VIOLATION_TYPE', 'EEZ_VIOLATION',   1, 'EEZ 침범',      'EEZ Violation',     10, '#EF4444'),
('VIOLATION_TYPE:DARK_VESSEL',        'VIOLATION_TYPE',  'VIOLATION_TYPE', 'DARK_VESSEL',     1, '다크베셀',      'Dark Vessel',       20, '#7C3AED'),
('VIOLATION_TYPE:MMSI_TAMPERING',     'VIOLATION_TYPE',  'VIOLATION_TYPE', 'MMSI_TAMPERING',  1, 'MMSI 변조',     'MMSI Tampering',    30, '#F59E0B'),
('VIOLATION_TYPE:ILLEGAL_TRANSSHIP',  'VIOLATION_TYPE',  'VIOLATION_TYPE', 'ILLEGAL_TRANSSHIP',1,'불법환적',      'Illegal Transship', 40, '#EC4899'),
('VIOLATION_TYPE:ILLEGAL_GEAR',       'VIOLATION_TYPE',  'VIOLATION_TYPE', 'ILLEGAL_GEAR',    1, '어구 불법',     'Illegal Gear',      50, '#F97316'),
('VIOLATION_TYPE:ZONE_DEPARTURE',     'VIOLATION_TYPE',  'VIOLATION_TYPE', 'ZONE_DEPARTURE',  1, '조업구역 이탈', 'Zone Departure',    60, '#06B6D4'),
('VIOLATION_TYPE:RISK_BEHAVIOR',      'VIOLATION_TYPE',  'VIOLATION_TYPE', 'RISK_BEHAVIOR',   1, '위험 행동',     'Risk Behavior',     70, '#64748B');

-- ============================================================
-- 이벤트 레벨 (EVENT_LEVEL)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('EVENT_LEVEL',              NULL,           'EVENT_LEVEL', 'EVENT_LEVEL', 0, '이벤트 심각도', 'Event Level',  20, NULL),
('EVENT_LEVEL:CRITICAL',     'EVENT_LEVEL',  'EVENT_LEVEL', 'CRITICAL',    1, '심각',          'Critical',     10, '#EF4444'),
('EVENT_LEVEL:HIGH',         'EVENT_LEVEL',  'EVENT_LEVEL', 'HIGH',        1, '높음',          'High',         20, '#F59E0B'),
('EVENT_LEVEL:MEDIUM',       'EVENT_LEVEL',  'EVENT_LEVEL', 'MEDIUM',      1, '보통',          'Medium',       30, '#3B82F6'),
('EVENT_LEVEL:LOW',          'EVENT_LEVEL',  'EVENT_LEVEL', 'LOW',         1, '낮음',          'Low',          40, '#6B7280');

-- ============================================================
-- 이벤트 상태 (EVENT_STATUS)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('EVENT_STATUS',                 NULL,            'EVENT_STATUS', 'EVENT_STATUS',  0, '이벤트 상태', 'Event Status',   30, NULL),
('EVENT_STATUS:NEW',             'EVENT_STATUS',  'EVENT_STATUS', 'NEW',           1, '신규',        'New',            10, '#EF4444'),
('EVENT_STATUS:ACK',             'EVENT_STATUS',  'EVENT_STATUS', 'ACK',           1, '확인',        'Acknowledged',   20, '#F59E0B'),
('EVENT_STATUS:IN_PROGRESS',     'EVENT_STATUS',  'EVENT_STATUS', 'IN_PROGRESS',   1, '처리중',      'In Progress',    30, '#3B82F6'),
('EVENT_STATUS:RESOLVED',        'EVENT_STATUS',  'EVENT_STATUS', 'RESOLVED',      1, '완료',        'Resolved',       40, '#22C55E'),
('EVENT_STATUS:FALSE_POSITIVE',  'EVENT_STATUS',  'EVENT_STATUS', 'FALSE_POSITIVE',1, '오탐',        'False Positive', 50, '#6B7280');

-- ============================================================
-- 이벤트 카테고리 (EVENT_CATEGORY) — 이벤트 유형 세분화
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('EVENT_CATEGORY',                    NULL,               'EVENT_CATEGORY', 'EVENT_CATEGORY',   0, '이벤트 유형',   'Event Category',   35, NULL),
('EVENT_CATEGORY:EEZ_INTRUSION',      'EVENT_CATEGORY',   'EVENT_CATEGORY', 'EEZ_INTRUSION',    1, 'EEZ 침범',      'EEZ Intrusion',    10, '#EF4444'),
('EVENT_CATEGORY:DARK_VESSEL',        'EVENT_CATEGORY',   'EVENT_CATEGORY', 'DARK_VESSEL',      1, '다크베셀',      'Dark Vessel',      20, '#7C3AED'),
('EVENT_CATEGORY:FLEET_CLUSTER',      'EVENT_CATEGORY',   'EVENT_CATEGORY', 'FLEET_CLUSTER',    1, '선단밀집',      'Fleet Cluster',    30, '#F97316'),
('EVENT_CATEGORY:ILLEGAL_TRANSSHIP',  'EVENT_CATEGORY',   'EVENT_CATEGORY', 'ILLEGAL_TRANSSHIP',1, '불법환적',      'Illegal Transship',40, '#EC4899'),
('EVENT_CATEGORY:MMSI_TAMPERING',     'EVENT_CATEGORY',   'EVENT_CATEGORY', 'MMSI_TAMPERING',   1, 'MMSI 변조',     'MMSI Tampering',   50, '#F59E0B'),
('EVENT_CATEGORY:AIS_LOSS',           'EVENT_CATEGORY',   'EVENT_CATEGORY', 'AIS_LOSS',         1, 'AIS 소실',      'AIS Loss',         60, '#64748B'),
('EVENT_CATEGORY:SPEED_ANOMALY',      'EVENT_CATEGORY',   'EVENT_CATEGORY', 'SPEED_ANOMALY',    1, '속력 이상',     'Speed Anomaly',    70, '#06B6D4'),
('EVENT_CATEGORY:ZONE_DEPARTURE',     'EVENT_CATEGORY',   'EVENT_CATEGORY', 'ZONE_DEPARTURE',   1, '구역 이탈',     'Zone Departure',   80, '#8B5CF6'),
('EVENT_CATEGORY:GEAR_ILLEGAL',       'EVENT_CATEGORY',   'EVENT_CATEGORY', 'GEAR_ILLEGAL',     1, '불법어구',      'Illegal Gear',     90, '#F97316'),
('EVENT_CATEGORY:AIS_RESUME',         'EVENT_CATEGORY',   'EVENT_CATEGORY', 'AIS_RESUME',       1, 'AIS 재송출',    'AIS Resume',       100, '#22C55E');

-- ============================================================
-- 단속 조치 유형 (ENFORCEMENT_ACTION)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('ENFORCEMENT_ACTION',              NULL,                   'ENFORCEMENT_ACTION', 'ENFORCEMENT_ACTION', 0, '단속 조치', 'Enforcement Action', 40, NULL),
('ENFORCEMENT_ACTION:CAPTURE',      'ENFORCEMENT_ACTION',   'ENFORCEMENT_ACTION', 'CAPTURE',            1, '나포',       'Capture',           10, '#EF4444'),
('ENFORCEMENT_ACTION:INSPECT',      'ENFORCEMENT_ACTION',   'ENFORCEMENT_ACTION', 'INSPECT',            1, '검문',       'Inspect',           20, '#F59E0B'),
('ENFORCEMENT_ACTION:WARN',         'ENFORCEMENT_ACTION',   'ENFORCEMENT_ACTION', 'WARN',               1, '경고',       'Warn',              30, '#3B82F6'),
('ENFORCEMENT_ACTION:DISPERSE',     'ENFORCEMENT_ACTION',   'ENFORCEMENT_ACTION', 'DISPERSE',           1, '퇴거',       'Disperse',          40, '#8B5CF6'),
('ENFORCEMENT_ACTION:TRACK',        'ENFORCEMENT_ACTION',   'ENFORCEMENT_ACTION', 'TRACK',              1, '추적',       'Track',             50, '#06B6D4'),
('ENFORCEMENT_ACTION:EVIDENCE',     'ENFORCEMENT_ACTION',   'ENFORCEMENT_ACTION', 'EVIDENCE',           1, '증거수집',   'Evidence',          60, '#64748B');

-- ============================================================
-- 단속 결과 (ENFORCEMENT_RESULT)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('ENFORCEMENT_RESULT',                  NULL,                    'ENFORCEMENT_RESULT', 'ENFORCEMENT_RESULT', 0, '단속 결과',  'Enforcement Result', 50, NULL),
('ENFORCEMENT_RESULT:PUNISHED',         'ENFORCEMENT_RESULT',    'ENFORCEMENT_RESULT', 'PUNISHED',           1, '처벌',        'Punished',          10, '#EF4444'),
('ENFORCEMENT_RESULT:WARNED',           'ENFORCEMENT_RESULT',    'ENFORCEMENT_RESULT', 'WARNED',             1, '경고',        'Warned',            20, '#F59E0B'),
('ENFORCEMENT_RESULT:RELEASED',         'ENFORCEMENT_RESULT',    'ENFORCEMENT_RESULT', 'RELEASED',           1, '훈방',        'Released',          30, '#22C55E'),
('ENFORCEMENT_RESULT:REFERRED',         'ENFORCEMENT_RESULT',    'ENFORCEMENT_RESULT', 'REFERRED',           1, '수사의뢰',    'Referred',          40, '#7C3AED'),
('ENFORCEMENT_RESULT:FALSE_POSITIVE',   'ENFORCEMENT_RESULT',    'ENFORCEMENT_RESULT', 'FALSE_POSITIVE',     1, '오탐(정상)',   'False Positive',    50, '#6B7280');

-- ============================================================
-- AI 일치도 (AI_MATCH)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('AI_MATCH',              NULL,         'AI_MATCH', 'AI_MATCH', 0, 'AI 일치도',  'AI Match',     60, NULL),
('AI_MATCH:MATCH',        'AI_MATCH',   'AI_MATCH', 'MATCH',    1, '일치',        'Match',       10, '#22C55E'),
('AI_MATCH:PARTIAL',      'AI_MATCH',   'AI_MATCH', 'PARTIAL',  1, '부분일치',    'Partial',     20, '#F59E0B'),
('AI_MATCH:MISMATCH',     'AI_MATCH',   'AI_MATCH', 'MISMATCH', 1, '불일치',      'Mismatch',    30, '#EF4444');

-- ============================================================
-- 다크베셀 패턴 (DARK_PATTERN)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('DARK_PATTERN',                            NULL,             'DARK_PATTERN', 'DARK_PATTERN',          0, '다크베셀 패턴',  'Dark Pattern',            70, NULL),
('DARK_PATTERN:COMPLETE_BLACKOUT',          'DARK_PATTERN',   'DARK_PATTERN', 'COMPLETE_BLACKOUT',     1, 'AIS 완전차단',    'Complete Blackout',      10, '#EF4444'),
('DARK_PATTERN:INTERMITTENT',              'DARK_PATTERN',   'DARK_PATTERN', 'INTERMITTENT',          1, '간헐 송출',       'Intermittent',           20, '#F59E0B'),
('DARK_PATTERN:MMSI_SPOOFING',            'DARK_PATTERN',   'DARK_PATTERN', 'MMSI_SPOOFING',         1, 'MMSI 변경 의심',  'MMSI Spoofing',          30, '#F97316'),
('DARK_PATTERN:ZONE_BOUNDARY_DISAPPEAR',  'DARK_PATTERN',   'DARK_PATTERN', 'ZONE_BOUNDARY_DISAPPEAR',1,'수역 경계 소실',  'Zone Boundary Disappear',40, '#7C3AED'),
('DARK_PATTERN:RAPID_REAPPEAR',           'DARK_PATTERN',   'DARK_PATTERN', 'RAPID_REAPPEAR',        1, '급재출현',        'Rapid Reappear',         50, '#EC4899'),
('DARK_PATTERN:SCHEDULED_BLACKOUT',       'DARK_PATTERN',   'DARK_PATTERN', 'SCHEDULED_BLACKOUT',    1, '정기 차단(저위험)','Scheduled Blackout',    60, '#6B7280');

-- ============================================================
-- 허가 상태 (PERMIT_STATUS)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('PERMIT_STATUS',              NULL,              'PERMIT_STATUS', 'PERMIT_STATUS', 0, '허가 상태',  'Permit Status', 80, NULL),
('PERMIT_STATUS:PERMITTED',    'PERMIT_STATUS',   'PERMIT_STATUS', 'PERMITTED',     1, '유효',        'Permitted',    10, '#22C55E'),
('PERMIT_STATUS:EXPIRED',      'PERMIT_STATUS',   'PERMIT_STATUS', 'EXPIRED',       1, '기간 초과',   'Expired',      20, '#F59E0B'),
('PERMIT_STATUS:NONE',         'PERMIT_STATUS',   'PERMIT_STATUS', 'NONE',          1, '무허가',      'None',         30, '#EF4444'),
('PERMIT_STATUS:REVOKED',      'PERMIT_STATUS',   'PERMIT_STATUS', 'REVOKED',       1, '취소',        'Revoked',      40, '#7C3AED'),
('PERMIT_STATUS:UNKNOWN',      'PERMIT_STATUS',   'PERMIT_STATUS', 'UNKNOWN',       1, '미상',        'Unknown',      50, '#6B7280');

-- ============================================================
-- 어구 판정 (GEAR_JUDGMENT) — illegal_gear_classifier 산출
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('GEAR_JUDGMENT',                      NULL,              'GEAR_JUDGMENT', 'GEAR_JUDGMENT',   0, '어구 판정',     'Gear Judgment', 90, NULL),
('GEAR_JUDGMENT:LEGAL',                'GEAR_JUDGMENT',   'GEAR_JUDGMENT', 'LEGAL',           1, '합법',          'Legal',         10, '#22C55E'),
('GEAR_JUDGMENT:NO_PERMIT',            'GEAR_JUDGMENT',   'GEAR_JUDGMENT', 'NO_PERMIT',       1, '무허가',        'No Permit',     20, '#EF4444'),
('GEAR_JUDGMENT:GEAR_MISMATCH',        'GEAR_JUDGMENT',   'GEAR_JUDGMENT', 'GEAR_MISMATCH',   1, '어구 불일치',   'Gear Mismatch', 30, '#F59E0B'),
('GEAR_JUDGMENT:ZONE_VIOLATION',       'GEAR_JUDGMENT',   'GEAR_JUDGMENT', 'ZONE_VIOLATION',  1, '해역 위반',     'Zone Violation',40, '#F97316'),
('GEAR_JUDGMENT:SEASON_VIOLATION',     'GEAR_JUDGMENT',   'GEAR_JUDGMENT', 'SEASON_VIOLATION',1, '금어기 위반',   'Season Violation',50,'#7C3AED');

-- ============================================================
-- 함정 상태 (PATROL_STATUS)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('PATROL_STATUS',                  NULL,              'PATROL_STATUS', 'PATROL_STATUS', 0, '함정 상태', 'Patrol Status', 100, NULL),
('PATROL_STATUS:AVAILABLE',        'PATROL_STATUS',   'PATROL_STATUS', 'AVAILABLE',     1, '가용',       'Available',    10, '#22C55E'),
('PATROL_STATUS:ON_PATROL',        'PATROL_STATUS',   'PATROL_STATUS', 'ON_PATROL',     1, '초계중',     'On Patrol',    20, '#3B82F6'),
('PATROL_STATUS:IN_PURSUIT',       'PATROL_STATUS',   'PATROL_STATUS', 'IN_PURSUIT',    1, '추적중',     'In Pursuit',   30, '#EF4444'),
('PATROL_STATUS:INSPECTING',       'PATROL_STATUS',   'PATROL_STATUS', 'INSPECTING',    1, '검문중',     'Inspecting',   40, '#F59E0B'),
('PATROL_STATUS:RETURNING',        'PATROL_STATUS',   'PATROL_STATUS', 'RETURNING',     1, '귀항중',     'Returning',    50, '#8B5CF6'),
('PATROL_STATUS:STANDBY',          'PATROL_STATUS',   'PATROL_STATUS', 'STANDBY',       1, '대기',       'Standby',      60, '#64748B'),
('PATROL_STATUS:MAINTENANCE',      'PATROL_STATUS',   'PATROL_STATUS', 'MAINTENANCE',   1, '정비중',     'Maintenance',  70, '#6B7280');

-- ============================================================
-- 선박 국적 (VESSEL_FLAG)
-- ============================================================
INSERT INTO kcg.code_master (code_id, parent_id, group_code, code, depth, name_ko, name_en, sort_order, color_hex) VALUES
('VESSEL_FLAG',            NULL,            'VESSEL_FLAG', 'VESSEL_FLAG', 0, '선박 국적',   'Vessel Flag', 110, NULL),
('VESSEL_FLAG:CN',         'VESSEL_FLAG',   'VESSEL_FLAG', 'CN',          1, '중국',         'China',      10, '#EF4444'),
('VESSEL_FLAG:KR',         'VESSEL_FLAG',   'VESSEL_FLAG', 'KR',          1, '한국',         'Korea',      20, '#3B82F6'),
('VESSEL_FLAG:JP',         'VESSEL_FLAG',   'VESSEL_FLAG', 'JP',          1, '일본',         'Japan',      30, '#22C55E'),
('VESSEL_FLAG:RU',         'VESSEL_FLAG',   'VESSEL_FLAG', 'RU',          1, '러시아',       'Russia',     40, '#F59E0B'),
('VESSEL_FLAG:UNKNOWN',    'VESSEL_FLAG',   'VESSEL_FLAG', 'UNKNOWN',     1, '미상',         'Unknown',    50, '#6B7280');
