// post.js
// Copyright (C) 2021 Digital Telepresence, LLC
// License: Apache-2.0

'use strict';

const path = require('path');
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const {
  ResourceStats,
  ResourceStatsDefaults,
} = require(path.join(__dirname, 'lib', 'resource-stats.js'));

const POST_STATUS_LIST = ['draft','published','archived'];

const PostSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, index: -1 },
  updated: { type: Date },
  authorType: { type: String, enum: ['User', 'CoreUser'], required: true },
  author: { type: Schema.ObjectId, required: true, index: 1, refPath: 'authorType' },
  image: { type: Schema.ObjectId, ref: 'Image' },
  title: { type: String, required: true },
  tags: { type: [String], lowercase: true },
  slug: { type: String, required: true, lowercase: true, unique: true },
  summary: { type: String },
  content: { type: String, select: false },
  status: { type: String, enum: POST_STATUS_LIST, default: 'draft', index: true },
  stats: { type: ResourceStats, default: ResourceStatsDefaults, required: true },
  flags: {
    enableComments: { type: Boolean, default: true, index: true },
    isFeatured: { type: Boolean, default: false, index: true },
  },
});

PostSchema.index({
  authorType: 1,
  author: 1,
  status: 1,
}, {
  name: 'post_author_by_type',
});

module.exports = mongoose.model('Post', PostSchema);