/**
 * POS-002 — Extend `backoffice_users.role` CHECK to include POS roles.
 *
 * New roles: `pos_cashier`, `pos_manager`. The application-side enum
 * (`Role` in `project/src/shared/auth.ts`) is updated in the same ticket.
 *
 * Idempotent: `IF EXISTS` on the old constraint + `IF NOT EXISTS` guard on
 * the new one.
 *
 * @param {import('node-pg-migrate').MigrationBuilder} pgm
 */

export const up = (pgm) => {
  pgm.sql(`ALTER TABLE backoffice_users DROP CONSTRAINT IF EXISTS backoffice_users_role_check`);
  pgm.sql(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'backoffice_users_role_check'
      ) THEN
        ALTER TABLE backoffice_users
          ADD CONSTRAINT backoffice_users_role_check
          CHECK (role IN ('admin','editor','pos_cashier','pos_manager'));
      END IF;
    END $$
  `);
};

export const down = (pgm) => {
  pgm.sql(`ALTER TABLE backoffice_users DROP CONSTRAINT IF EXISTS backoffice_users_role_check`);
  pgm.sql(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'backoffice_users_role_check'
      ) THEN
        ALTER TABLE backoffice_users
          ADD CONSTRAINT backoffice_users_role_check
          CHECK (role IN ('admin','editor'));
      END IF;
    END $$
  `);
};
