SET @scope_col_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'operation_audit_log'
      AND COLUMN_NAME = 'scope'
);

SET @add_scope_col_sql = IF(
    @scope_col_exists = 0,
    'ALTER TABLE operation_audit_log ADD COLUMN scope VARCHAR(16) NOT NULL DEFAULT ''TENANT'' AFTER user_id',
    'SELECT 1'
);
PREPARE stmt_add_scope_col FROM @add_scope_col_sql;
EXECUTE stmt_add_scope_col;
DEALLOCATE PREPARE stmt_add_scope_col;

UPDATE operation_audit_log
SET scope = CASE WHEN tenant_id = 0 THEN 'PLATFORM' ELSE 'TENANT' END
WHERE scope IS NULL OR scope = '';

SET @scope_idx_exists = (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'operation_audit_log'
      AND INDEX_NAME = 'idx_scope_time'
);
SET @add_scope_idx_sql = IF(
    @scope_idx_exists = 0,
    'ALTER TABLE operation_audit_log ADD KEY idx_scope_time (scope, created_at)',
    'SELECT 1'
);
PREPARE stmt_add_scope_idx FROM @add_scope_idx_sql;
EXECUTE stmt_add_scope_idx;
DEALLOCATE PREPARE stmt_add_scope_idx;
