const mongoose = require('mongoose')
const aggregatePaginate = require('mongoose-aggregate-paginate-v2')
const MongoPaging = require('mongo-cursor-pagination')

const schema = {
  _id: false,
  cve_id: String,
  cve_year: String,
  state: String,
  owning_cna: String,
  requested_by: {
    cna: String,
    user: String
  },
  reserved: Date,
  time: {
    created: Date,
    modified: Date
  }
}

if (process.env.NODE_ENV === 'test') {
  schema.reserved = { type: Date, default: Date.now }
}

const CveIdSchema = new mongoose.Schema(schema, { collection: 'Cve-Id', timestamps: { createdAt: 'time.created', updatedAt: 'time.modified' } })

CveIdSchema.query.byCveId = function (cveId) {
  return this.where({ cve_id: cveId })
}

CveIdSchema.index({ cve_id: 1 })
CveIdSchema.index({ owning_cna: 1, state: 1 })
CveIdSchema.index({ reserved: 1 })

CveIdSchema.plugin(aggregatePaginate)

// Cursor pagination
CveIdSchema.plugin(MongoPaging.mongoosePlugin)
const CveId = mongoose.model('Cve-Id', CveIdSchema)

module.exports = CveId
