const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CounterSchema = Schema({
  '_id': { 'type': String, 'required': true },
  'seq': { 'type': Number, 'default': 1000 }
});

const counter = mongoose.model('counter', CounterSchema);

// create a schema for our links
const urlSchema = new Schema({
  '_id': { 'type': Number, 'index': true },
  'long_url': String,
  'created_at': Date,
  'visits': { 'type': Number, 'default': 0 }
});

urlSchema.pre('save', function(next) {
  const doc = this;
  counter.findByIdAndUpdate({ '_id': 'url_count' }, { '$inc': { 'seq': 1 } }, function(error, counter) {
    if (error)
      return next(error);
    doc.created_at = new Date();
    doc._id = counter.seq;
    next();
  });
});

const Url = mongoose.model('Url', urlSchema);

module.exports = Url;
