import thinky from '../thinky';

let type = thinky.type;

// `Set` already exists. Use Set_ (note that models.Set will be used and not models.Set_)
let Set_ = thinky.createModel('Set', {
    id       : type.string().optional(), // Optional => not specified in bodies but generated by RethinkDB
    name     : String,
    createdAt: type.date().default(new Date()),
    editedAt : Date,
    isRemoved: type.boolean().default(false)
}, {
    enforce_missing: true,
    enforce_extra  : 'remove',
    enforce_type   : 'strict'
});

Set_.pre('save', function (next) {
    this.editedAt = new Date();
    next();
});

Set_.ensureIndex('name');
Set_.ensureIndex('createdAt');
Set_.ensureIndex('editedAt');

Set_.associate = models => {
    // n:n instead of 1:n to allow one promotion containing multiple times the same set
    models.Set.hasAndBelongsToMany(models.Promotion, 'promotion', 'id', 'id');
    models.Set.hasAndBelongsToMany(models.Article, 'articles', 'id', 'id');
};

export default Set_;
