-- Add `source` column to app_calls to distinguish auto-captured calls (source='auto')
-- from manually submitted calls (source=NULL).
-- Compatible with older MySQL/MariaDB without `ADD COLUMN IF NOT EXISTS`.

SET @db := DATABASE();

SET @sql := IF(
    (SELECT COUNT(*) FROM information_schema.COLUMNS
     WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'app_calls' AND COLUMN_NAME = 'source') = 0,
    'ALTER TABLE app_calls ADD COLUMN source VARCHAR(32) NULL DEFAULT NULL AFTER direction',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Index to query auto-captured calls efficiently
SET @sql := IF(
    (SELECT COUNT(*) FROM information_schema.STATISTICS
     WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'app_calls' AND INDEX_NAME = 'idx_source') = 0,
    'ALTER TABLE app_calls ADD INDEX idx_source (source)',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
