// user.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const {
  ResourceStats,
  ResourceStatsDefaults,
} = require('./lib/resource-stats');

const {
  DTP_THEME_LIST,
  UserFlagsSchema,
  UserPermissionsSchema,
  UserOptInSchema,
} = require('./lib/user-types');

const UserSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, index: -1 },
  email: { type: String, required: true, lowercase: true, unique: true },
  username: { type: String, required: true },
  username_lc: { type: String, required: true, lowercase: true, unique: true, index: 1 },
  passwordSalt: { type: String, required: true },
  password: { type: String, required: true },
  displayName: { type: String },
  bio: { type: String, maxlength: 300 },
  picture: {
    large: { type: Schema.ObjectId, ref: 'Image' },
    small: { type: Schema.ObjectId, ref: 'Image' },
  },
  badges: { type: [String] },
  flags: { type: UserFlagsSchema, select: false },
  permissions: { type: UserPermissionsSchema, select: false },
  optIn: { type: UserOptInSchema, required: true, select: false },
  theme: { type: String, enum: DTP_THEME_LIST, default: 'dtp-light', required: true },
  resourceStats: { type: ResourceStats, default: ResourceStatsDefaults, required: true },
  lastAnnouncement: { type: Date },
}, {
  toObject: { virtuals: true },
});

UserSchema.virtual('hasAuthorPermissions').get( function ( ) {
  return this.permissions.canAuthorPosts;
});

UserSchema.virtual('hasPublishPermissions').get( function ( ) {
  return this.permissions.canPublishPages || this.permissions.canPublishPosts;
});

UserSchema.virtual('hasAuthorDashboard').get( function ( ) {
  return this.permissions.cahAuthorPosts || 
    this.permissions.canPublishPosts ||
    this.flags.isAdmin;
});

module.exports = mongoose.model('User', UserSchema);
