/** Payment transactions and idempotency. */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE payments_transactions (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      provider text NOT NULL,
      provider_event_id text NOT NULL,
      provider_payment_id text,
      order_id uuid,
      amount_cents integer NOT NULL,
      currency text NOT NULL DEFAULT 'EUR',
      status text NOT NULL,
      raw jsonb NOT NULL DEFAULT '{}'::jsonb,
      created_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT payments_transactions_amount_non_negative CHECK (amount_cents >= 0),
      CONSTRAINT payments_transactions_status_check CHECK (status IN ('requires_payment','succeeded','failed','refunded','chargeback')),
      CONSTRAINT payments_transactions_currency_check CHECK (currency = 'EUR'),
      CONSTRAINT payments_transactions_provider_event_unique UNIQUE (provider, provider_event_id)
    )
  `);
  pgm.sql('CREATE INDEX payments_transactions_order_id_idx ON payments_transactions (order_id)');
};

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