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

'use strict';

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

const RECIPIENT_TYPE_LIST = ['User','CoreUser'];
const EMITTER_TYPE_LIST = ['User','CoreUser','OAuth2Client'];

const KaleidoscopeEventSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, index: -1, expires: '30d' },
  recipientType: { type: String, enum: RECIPIENT_TYPE_LIST },
  recipient: { type: Schema.ObjectId, index: 1, refPath: 'recipientType' },
  action: { type: String, required: true, lowercase: true },
  label: { type: String },
  content: { type: String },
  href: { type: String },
  thumbnail: { type: String },
  source: {
    pkg: {
      name: { type: String, required: true },
      version: { type: String, required: true },
    },
    site: {
      name: { type: String, required: true },
      description: { type: String },
      domain: { type: String, lowercase: true, required: true },
      domainKey: { type: String, lowercase: true, required: true },
      company: { type: String },
      coreAuth: {
        scopes: { type: [String] },
      },
    },
    emitter: {
      emitterType: { type: String, enum: EMITTER_TYPE_LIST },
      emitterId: { type: Schema.ObjectId, refPath: 'source.emitter.emitterType' },
      displayName: { type: String },
      username: { type: String },
      href: { type: String },
    },
  },
  attachmentType: { type: String },
  attachment: { type: Schema.ObjectId, refPath: 'attachmentType' },
});

/*
 * Compound index for site.domainKey, author.userId for when local members
 * subscribe to a specific author on a domain, or the whole domain.
 */
KaleidoscopeEventSchema.index({
  'source.site.domainKey': 1,
  'source.emitter.emitterId': 1,
}, {
  name: 'evtsrc_site_author_index',
});

module.exports = mongoose.model('KaleidoscopeEvent', KaleidoscopeEventSchema);