BEGIN;

ALTER TABLE subscriptions
  ADD COLUMN IF NOT EXISTS activation_date text,
  ADD COLUMN IF NOT EXISTS first_payment_date text,
  ADD COLUMN IF NOT EXISTS end_date text,
  ADD COLUMN IF NOT EXISTS occurrence_count integer,
  ADD COLUMN IF NOT EXISTS custom_interval_days integer;

DO $$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM information_schema.columns
    WHERE table_name = 'subscriptions' AND column_name = 'renewal_date'
  ) THEN
    UPDATE subscriptions
    SET
      activation_date = COALESCE(activation_date, renewal_date),
      first_payment_date = COALESCE(first_payment_date, renewal_date),
      subscription_status = CASE
        WHEN subscription_status = 'disabled' THEN 'terminated'
        ELSE subscription_status
      END;
  ELSE
    UPDATE subscriptions
    SET subscription_status = 'terminated'
    WHERE subscription_status = 'disabled';
  END IF;
END $$;

ALTER TABLE subscriptions
  ALTER COLUMN activation_date SET NOT NULL,
  ALTER COLUMN first_payment_date SET NOT NULL;

ALTER TABLE subscriptions
  DROP COLUMN IF EXISTS renewal_date,
  DROP COLUMN IF EXISTS auto_renew;

DROP INDEX IF EXISTS subscriptions_renewal_date_idx;
CREATE INDEX IF NOT EXISTS subscriptions_first_payment_date_idx
  ON subscriptions(first_payment_date);

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_occurrence_count_positive'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_occurrence_count_positive
      CHECK (occurrence_count > 0);
  END IF;
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_custom_interval_days_positive'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_custom_interval_days_positive
      CHECK (custom_interval_days > 0);
  END IF;
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_amount_positive'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_amount_positive CHECK (amount > 0);
  END IF;
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_billing_cycle_valid'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_billing_cycle_valid
      CHECK (billing_cycle IN ('weekly', 'monthly', 'yearly', 'custom'));
  END IF;
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_status_valid'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_status_valid
      CHECK (subscription_status IN ('active', 'suspended', 'terminated'));
  END IF;
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'subscriptions_dates_valid'
  ) THEN
    ALTER TABLE subscriptions
      ADD CONSTRAINT subscriptions_dates_valid
      CHECK (
        activation_date <= first_payment_date
        AND (end_date IS NULL OR end_date >= first_payment_date)
      );
  END IF;
END $$;

COMMIT;
