SET @sql = (
    SELECT IF(
        EXISTS (
            SELECT 1
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = 'apaczka_integration_settings'
              AND column_name = 'app_id'
        ),
        'SELECT 1',
        'ALTER TABLE apaczka_integration_settings ADD COLUMN app_id VARCHAR(128) NULL AFTER integration_id'
    )
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = (
    SELECT IF(
        EXISTS (
            SELECT 1
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = 'apaczka_integration_settings'
              AND column_name = 'app_secret_encrypted'
        ),
        'SELECT 1',
        'ALTER TABLE apaczka_integration_settings ADD COLUMN app_secret_encrypted TEXT NULL AFTER app_id'
    )
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE apaczka_integration_settings
SET app_secret_encrypted = api_key_encrypted
WHERE (app_secret_encrypted IS NULL OR app_secret_encrypted = '')
  AND api_key_encrypted IS NOT NULL
  AND api_key_encrypted <> '';
