/** Promotions and selected cart promo code. */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE promotions_promotions (
      code text PRIMARY KEY,
      type text NOT NULL,
      value integer NOT NULL,
      starts_at timestamptz NOT NULL,
      ends_at timestamptz NOT NULL,
      usage_limit integer,
      usage_count integer NOT NULL DEFAULT 0,
      active boolean NOT NULL DEFAULT true,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT promotions_type_check CHECK (type IN ('percent', 'fixed_amount')),
      CONSTRAINT promotions_value_positive CHECK (value > 0),
      CONSTRAINT promotions_usage_limit_positive CHECK (usage_limit IS NULL OR usage_limit > 0),
      CONSTRAINT promotions_usage_count_non_negative CHECK (usage_count >= 0),
      CONSTRAINT promotions_window_check CHECK (ends_at > starts_at)
    )
  `);
  pgm.sql('ALTER TABLE cart_carts ADD COLUMN promo_code text');
};

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const down = (pgm) => {
  pgm.sql('ALTER TABLE cart_carts DROP COLUMN IF EXISTS promo_code');
  pgm.sql('DROP TABLE IF EXISTS promotions_promotions');
};
