// core-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 CoreUserSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, index: -1 },
  updated: { type: Date, default: Date.now, required: true, index: -1 },
  core: { type: Schema.ObjectId, required: true, ref: 'CoreNode' },
  coreUserId: { type: Schema.ObjectId, required: true },
  username: { type: String, required: true },
  username_lc: { type: String, required: true, lowercase: true, index: 1 },
  displayName: { type: String },
  bio: { type: String, maxlength: 300 },
  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 },
});

CoreUserSchema.index({
  core: 1,
  coreUserId: 1,
}, {
  unique: true,
  name: 'core_userId_unique',
});

CoreUserSchema.index({
  core: 1,
  username_lc: 1,
}, {
  unique: true,
  name: 'core_username_lc_unique',
});

module.exports = mongoose.model('CoreUser', CoreUserSchema);