-- code_detail: 플랫폼 공통 vs 지자체 전용 (cd_source, cd_lg_idx)
-- 여러 번 실행해도 이미 있으면 스킵 (MySQL / MariaDB)
--
-- 적용 예:
--   mysql -h 127.0.0.1 -u USER -p DBNAME < writable/database/code_detail_source_lg_add.sql

SET @schema = DATABASE();

-- cd_source
SET @col := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = 'code_detail' AND COLUMN_NAME = 'cd_source'
);
SET @sql := IF(@col = 0,
  'ALTER TABLE `code_detail` ADD COLUMN `cd_source` ENUM(''platform'', ''local'') NOT NULL DEFAULT ''platform'' COMMENT ''platform=CSV/시드 등 전역, local=지자체 관리자 등록'' AFTER `cd_ck_idx`',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- cd_lg_idx
SET @col := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = 'code_detail' AND COLUMN_NAME = 'cd_lg_idx'
);
SET @sql := IF(@col = 0,
  'ALTER TABLE `code_detail` ADD COLUMN `cd_lg_idx` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''0=전 지자체 공통, >0=해당 지자체 전용'' AFTER `cd_source`',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 보조 인덱스
SET @idx := (
  SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = 'code_detail' AND INDEX_NAME = 'idx_cd_lg_idx'
);
SET @sql := IF(@idx = 0,
  'ALTER TABLE `code_detail` ADD KEY `idx_cd_lg_idx` (`cd_lg_idx`)',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 테넌트별 코드 유일
SET @idx := (
  SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = 'code_detail' AND INDEX_NAME = 'uk_cd_tenant'
);
SET @sql := IF(@idx = 0,
  'ALTER TABLE `code_detail` ADD UNIQUE KEY `uk_cd_tenant` (`cd_ck_idx`, `cd_code`, `cd_lg_idx`)',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
