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


let grantSchema = new Schema({
  resource: { type: String, require: true, desc: '资源' },
  action: { type: String, enum: ['create', 'read', 'update', 'delete'], require: true, desc: '操作' },
  possession: { type: String, enum: ['own', 'any'], required: true, desc: '所属' },
  attributes: { type: String, required: 'true', default: '*', desc: '字段' },
})


let roleSchema = new Schema({

  name: { type: String, required: true, desc: '角色名称', searchable: true, },
  user: { type: Schema.Types.ObjectId, ref: 'User', desc: '创建者', },
  permissions: { type: [String], required: true, default: [], desc: '权限', listing: false, },
  time: { type: Date, default: Date.now, desc: '创建时间', },
  grants: { type: [grantSchema], default: [], desc: '授权', }

}, {
  toObject: {
    transform: roleTransform,
  },
  toJSON: {
    transform: roleTransform,
  }
});


function roleTransform(doc, ret) {
  /*
  if (doc.grants) {
    doc.grants = doc.grants || [];
    ret.grants = doc.grants.map(g => auth.base.translate(g));
    ret.grants = ret.grants.sort((a, b) => {
      if (a < b) return 1;
      if (a > b) return -1;
      return 0;
    })
  }
  */
}


module.exports = roleSchema;
