
SET @has_price_1m := (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'ad_products'
    AND COLUMN_NAME = 'price_1m_cents'
);
SET @sql_price_1m := IF(
  @has_price_1m = 0,
  'ALTER TABLE ad_products ADD COLUMN price_1m_cents INT UNSIGNED NOT NULL DEFAULT 0 AFTER monthly_amount_cents',
  'SELECT 1'
);
PREPARE stmt_price_1m FROM @sql_price_1m;
EXECUTE stmt_price_1m;
DEALLOCATE PREPARE stmt_price_1m;

UPDATE ad_products
SET price_1m_cents = CASE
    WHEN price_1m_cents > 0 THEN price_1m_cents
    WHEN price_3m_cents > 0 THEN price_3m_cents
    ELSE monthly_amount_cents
END;

UPDATE ad_products
SET price_12m_cents = CASE
    WHEN price_12m_cents > 0 THEN price_12m_cents
    WHEN price_6m_cents > 0 THEN price_6m_cents
    WHEN price_3m_cents > 0 THEN price_3m_cents
    ELSE monthly_amount_cents
END;

UPDATE ad_products
SET term_options_csv = '1,12'
WHERE term_options_csv IS NULL
   OR term_options_csv = ''
   OR term_options_csv IN ('3,6,12', '3,12', '6,12', '3,6');

ALTER TABLE ad_products
  ALTER COLUMN term_options_csv SET DEFAULT '1,12';

ALTER TABLE ad_subscriptions
  ALTER COLUMN term_months SET DEFAULT 1;

UPDATE ad_subscriptions
SET term_months = 1
WHERE term_months NOT IN (1,12);
