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

'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ATTACHMENT_STATUS_LIST = [
  'processing', // the attachment is in the processing queue
  'live',       // the attachment is available for use
  'rejected',   // the attachment was rejected (by proccessing queue)
  'retired',    // the attachment has been retired
];

const AttachmentFileSchema = new Schema({
  bucket: { type: String, required: true },
  key: { type: String, required: true },
  mime: { type: String, required: true },
  size: { type: Number, required: true },
  etag: { type: String, required: true },
}, {
  _id: false,
});

/*
 * Attachments are simply files. They can really be any kind of file, but will
 * mostly be image, video, and audio files.
 * 
 * owner is the User or CoreUser that uploaded the attachment.
 * 
 * item is the item to which the attachment is attached.
 */
const AttachmentSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, index: 1 },
  status: { type: String, enum: ATTACHMENT_STATUS_LIST, default: 'processing', required: true },
  ownerType: { type: String, required: true },
  owner: { type: Schema.ObjectId, required: true, index: 1, refPath: 'ownerType' },
  itemType: { type: String, required: true },
  item: { type: Schema.ObjectId, required: true, index: 1, refPath: 'itemType' },
  original: { type: AttachmentFileSchema, required: true, select: false },
  encoded: { type: AttachmentFileSchema, required: true },
  flags: {
    isSensitive: { type: Boolean, default: false, required: true },
  },
});

AttachmentSchema.index({
  ownerType: 1,
  owner: 1,
}, {
  name: 'attachment_owner_idx',
});

AttachmentSchema.index({
  itemType: 1,
  item: 1,
}, {
  name: 'attachment_item_idx',
});

module.exports = mongoose.model('Attachment', AttachmentSchema);