SET @c := (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND COLUMN_NAME = 'download_type'
);
SET @sql := IF(
    @c = 0,
    'ALTER TABLE template_download_log ADD COLUMN download_type VARCHAR(32) NOT NULL DEFAULT ''NORMAL'' AFTER object_key',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND COLUMN_NAME = 'watermark_text'
);
SET @sql := IF(
    @c = 0,
    'ALTER TABLE template_download_log ADD COLUMN watermark_text VARCHAR(255) NULL AFTER download_type',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND COLUMN_NAME = 'project_id'
);
SET @sql := IF(
    @c = 0,
    'ALTER TABLE template_download_log ADD COLUMN project_id BIGINT UNSIGNED NULL AFTER watermark_text',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND COLUMN_NAME = 'meeting_id'
);
SET @sql := IF(
    @c = 0,
    'ALTER TABLE template_download_log ADD COLUMN meeting_id BIGINT UNSIGNED NULL AFTER project_id',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @idx := (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND INDEX_NAME = 'idx_tenant_template_time'
);
SET @sql := IF(
    @idx = 0,
    'ALTER TABLE template_download_log ADD KEY idx_tenant_template_time (tenant_id, template_id, downloaded_at)',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @idx := (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND INDEX_NAME = 'idx_tenant_user_time'
);
SET @sql := IF(
    @idx = 0,
    'ALTER TABLE template_download_log ADD KEY idx_tenant_user_time (tenant_id, user_id, downloaded_at)',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @idx := (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'template_download_log' AND INDEX_NAME = 'idx_tenant_download_type_time'
);
SET @sql := IF(
    @idx = 0,
    'ALTER TABLE template_download_log ADD KEY idx_tenant_download_type_time (tenant_id, download_type, downloaded_at)',
    'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
