/** Cart persistence: product, variant and quantity only. */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE cart_carts (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id uuid NOT NULL UNIQUE,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now()
    )
  `);

  pgm.sql(`
    CREATE TABLE cart_items (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      cart_id uuid NOT NULL REFERENCES cart_carts(id) ON DELETE CASCADE,
      product_id uuid NOT NULL,
      variant_id uuid NOT NULL,
      quantity integer NOT NULL,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT cart_items_quantity_positive CHECK (quantity > 0),
      CONSTRAINT cart_items_unique_variant_per_cart UNIQUE (cart_id, variant_id)
    )
  `);
  pgm.sql('CREATE INDEX cart_items_cart_id_idx ON cart_items (cart_id)');
};

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