/**
 * Inventory stock counters and movement audit.
 */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE inventory_stock (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      variant_id uuid NOT NULL UNIQUE,
      available integer NOT NULL DEFAULT 0,
      reserved integer NOT NULL DEFAULT 0,
      sold integer NOT NULL DEFAULT 0,
      incoming integer NOT NULL DEFAULT 0,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT inventory_stock_available_non_negative CHECK (available >= 0),
      CONSTRAINT inventory_stock_reserved_non_negative CHECK (reserved >= 0),
      CONSTRAINT inventory_stock_sold_non_negative CHECK (sold >= 0),
      CONSTRAINT inventory_stock_incoming_non_negative CHECK (incoming >= 0)
    )
  `);
  pgm.sql('CREATE INDEX inventory_stock_variant_id_idx ON inventory_stock (variant_id)');

  pgm.sql(`
    CREATE TABLE inventory_movements (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      variant_id uuid NOT NULL,
      operation text NOT NULL,
      quantity integer NOT NULL,
      created_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT inventory_movements_quantity_non_negative CHECK (quantity >= 0),
      CONSTRAINT inventory_movements_operation_check
        CHECK (operation IN ('reserve', 'release', 'confirm', 'set_available'))
    )
  `);
  pgm.sql('CREATE INDEX inventory_movements_variant_id_idx ON inventory_movements (variant_id)');
};

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