-- V6: build_id support for multi-build-per-version sourcemap tracking
-- log_sourcemaps: add build_id, update unique key, add fallback index
-- log_issue_events: add build_id for exact symbolication matching

-- Conditional: add build_id to log_sourcemaps only if not exists
SET @col_exists = (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'log_sourcemaps' AND COLUMN_NAME = 'build_id'
);
SET @sql = IF(@col_exists = 0,
    'ALTER TABLE log_sourcemaps ADD COLUMN build_id VARCHAR(32) NULL COMMENT ''Gradle build timestamp yyyyMMddHHmmss; NULL = pre-V6 upload'' AFTER bundle_name',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Conditional: drop old uk_map key only if still exists
SET @key_exists = (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'log_sourcemaps' AND INDEX_NAME = 'uk_map'
);
SET @sql = IF(@key_exists > 0, 'ALTER TABLE log_sourcemaps DROP KEY uk_map', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Conditional: add uk_map_build unique key only if not exists
SET @key_exists = (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'log_sourcemaps' AND INDEX_NAME = 'uk_map_build'
);
SET @sql = IF(@key_exists = 0,
    'ALTER TABLE log_sourcemaps ADD UNIQUE KEY uk_map_build (app_key, platform, app_version, build_id, bundle_name)',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Conditional: add idx_sm_version_latest only if not exists
SET @key_exists = (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'log_sourcemaps' AND INDEX_NAME = 'idx_sm_version_latest'
);
SET @sql = IF(@key_exists = 0,
    'ALTER TABLE log_sourcemaps ADD INDEX idx_sm_version_latest (app_key, platform, app_version, bundle_name, uploaded_at)',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Conditional: add build_id to log_issue_events only if not exists
SET @col_exists = (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'log_issue_events' AND COLUMN_NAME = 'build_id'
);
SET @sql = IF(@col_exists = 0,
    'ALTER TABLE log_issue_events ADD COLUMN build_id VARCHAR(32) NULL COMMENT ''Matches log_sourcemaps.build_id for exact symbolication'' AFTER app_version',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
