exports.up = (pgm) => {
  pgm.createTable('trip_preference_overrides', {
    id: { type: 'uuid', primaryKey: true, default: pgm.func('gen_random_uuid()') },
    trip_id: { type: 'uuid', notNull: true, references: 'trips(id)', onDelete: 'CASCADE' },
    user_id: { type: 'uuid', references: 'users(id)' },
    traveler_id: { type: 'uuid', references: 'travelers(id)', onDelete: 'CASCADE' },
    overrides: { type: 'jsonb', notNull: true, default: '{}' },
    created_at: { type: 'timestamptz', notNull: true, default: pgm.func('now()') },
    updated_at: { type: 'timestamptz', notNull: true, default: pgm.func('now()') },
  });
  pgm.addConstraint(
    'trip_preference_overrides',
    'trip_preference_overrides_subject_check',
    'CHECK (num_nonnulls(user_id, traveler_id) = 1)',
  );
  pgm.createIndex('trip_preference_overrides', ['trip_id', 'user_id'], {
    unique: true,
    where: 'user_id IS NOT NULL',
    name: 'trip_pref_overrides_trip_user_uq',
  });
  pgm.createIndex('trip_preference_overrides', ['trip_id', 'traveler_id'], {
    unique: true,
    where: 'traveler_id IS NOT NULL',
    name: 'trip_pref_overrides_trip_traveler_uq',
  });
};

exports.down = (pgm) => {
  pgm.dropTable('trip_preference_overrides');
};
