BEGIN;

ALTER TABLE subscriptions
  ADD COLUMN IF NOT EXISTS custom_interval_value integer,
  ADD COLUMN IF NOT EXISTS custom_interval_unit text;

DO $$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM information_schema.columns
    WHERE table_name = 'subscriptions' AND column_name = 'custom_interval_days'
  ) THEN
    UPDATE subscriptions
    SET
      custom_interval_value = COALESCE(custom_interval_value, custom_interval_days),
      custom_interval_unit = CASE
        WHEN custom_interval_days IS NOT NULL THEN COALESCE(custom_interval_unit, 'days')
        ELSE custom_interval_unit
      END;
  END IF;
END $$;

ALTER TABLE subscriptions
  DROP COLUMN IF EXISTS custom_interval_days;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_custom_interval_value_positive'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_custom_interval_value_positive
      CHECK (custom_interval_value > 0);
  END IF;
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_custom_interval_unit_valid'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_custom_interval_unit_valid
      CHECK (custom_interval_unit IN ('days', 'weeks', 'months', 'years'));
  END IF;
END $$;

COMMIT;
