/** Orders with item snapshots and explicit state machine. */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE orders_orders (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id uuid NOT NULL,
      idempotency_key text UNIQUE,
      state text NOT NULL DEFAULT 'PENDING',
      currency text NOT NULL DEFAULT 'EUR',
      subtotal_cents integer NOT NULL DEFAULT 0,
      discount_cents integer NOT NULL DEFAULT 0,
      tax_cents integer NOT NULL DEFAULT 0,
      total_cents integer NOT NULL DEFAULT 0,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT orders_orders_state_check CHECK (state IN (
        'PENDING','AWAITING_PAYMENT','PAID','PROCESSING','SHIPPED','DELIVERED',
        'CANCELLED','REFUNDED','PARTIALLY_REFUNDED'
      )),
      CONSTRAINT orders_orders_currency_check CHECK (currency = 'EUR'),
      CONSTRAINT orders_orders_subtotal_non_negative CHECK (subtotal_cents >= 0),
      CONSTRAINT orders_orders_discount_non_negative CHECK (discount_cents >= 0),
      CONSTRAINT orders_orders_tax_non_negative CHECK (tax_cents >= 0),
      CONSTRAINT orders_orders_total_non_negative CHECK (total_cents >= 0)
    )
  `);
  pgm.sql('CREATE INDEX orders_orders_user_id_idx ON orders_orders (user_id)');

  pgm.sql(`
    CREATE TABLE orders_items (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      order_id uuid NOT NULL REFERENCES orders_orders(id) ON DELETE CASCADE,
      product_id uuid NOT NULL,
      variant_id uuid NOT NULL,
      sku text NOT NULL,
      ean text,
      name text NOT NULL,
      unit_price_cents integer NOT NULL,
      discount_cents integer NOT NULL DEFAULT 0,
      tax_cents integer NOT NULL DEFAULT 0,
      quantity integer NOT NULL,
      created_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT orders_items_quantity_positive CHECK (quantity > 0),
      CONSTRAINT orders_items_unit_price_non_negative CHECK (unit_price_cents >= 0),
      CONSTRAINT orders_items_discount_non_negative CHECK (discount_cents >= 0),
      CONSTRAINT orders_items_tax_non_negative CHECK (tax_cents >= 0)
    )
  `);
  pgm.sql('CREATE INDEX orders_items_order_id_idx ON orders_items (order_id)');
};

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