/*
 * F-187 — Safe POS cashier lifecycle.
 *
 * POS cashiers are referenced by cash sessions and receipt/reporting history.
 * Their rows therefore use deactivation/deletion tombstones instead of physical
 * deletion. Existing backoffice accounts remain active.
 *
 * @param {import('node-pg-migrate').MigrationBuilder} pgm
 */

export const up = (pgm) => {
  pgm.addColumns('backoffice_users', {
    active: { type: 'boolean', notNull: true, default: true },
    deactivated_at: { type: 'timestamptz' },
    deleted_at: { type: 'timestamptz' },
  });

  pgm.addConstraint('backoffice_users', 'backoffice_users_lifecycle_check', {
    check:
      '(active = true AND deactivated_at IS NULL AND deleted_at IS NULL) OR ' +
      '(active = false AND deactivated_at IS NOT NULL)',
  });

  pgm.createIndex('backoffice_users', ['role', 'active', 'deleted_at'], {
    name: 'backoffice_users_pos_cashier_lifecycle_idx',
    where: "role = 'pos_cashier'",
  });
};

export const down = (pgm) => {
  pgm.dropIndex('backoffice_users', ['role', 'active', 'deleted_at'], {
    name: 'backoffice_users_pos_cashier_lifecycle_idx',
    ifExists: true,
  });
  pgm.dropConstraint('backoffice_users', 'backoffice_users_lifecycle_check', {
    ifExists: true,
  });
  pgm.dropColumns('backoffice_users', ['active', 'deactivated_at', 'deleted_at'], {
    ifExists: true,
  });
};
