/**
 * POS-002 catch-up — Add the walk-in CHECK constraint to existing DBs.
 *
 * Migration 045 drops NOT NULL on `orders_orders.user_id` (so POS walk-in
 * sales work) but originally forgot the matching CHECK: ecommerce and admin
 * sales must still have a non-null user_id. This migration adds the CHECK
 * for DBs that already ran 045 before the fix landed.
 *
 * Idempotent: the constraint is added via `DO $$ IF NOT EXISTS ...`,
 * so re-running on a fresh DB that already has the CHECK (via 045) is a
 * no-op.
 *
 * @param {import('node-pg-migrate').MigrationBuilder} pgm
 */

export const up = (pgm) => {
  pgm.sql(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'orders_orders_user_required_when_not_pos'
      ) THEN
        ALTER TABLE orders_orders
          ADD CONSTRAINT orders_orders_user_required_when_not_pos
          CHECK (source = 'pos' OR user_id IS NOT NULL);
      END IF;
    END $$
  `);
};

export const down = (pgm) => {
  pgm.sql(`ALTER TABLE orders_orders DROP CONSTRAINT IF EXISTS orders_orders_user_required_when_not_pos`);
};
