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

'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const RoomMemberSchema = new Schema({
  memberType: { type: String, required: true },
  member: { type: Schema.ObjectId, required: true, refPath: 'members.memberType' },
});

const ROOM_VISIBILITY_LIST = ['public', 'private'];
const ROOM_MEMBERSHIP_POICY_LIST = ['open', 'closed'];

const ChatRoomSchema = new Schema({
  created: { type: Date, default: Date.now, required: true, index: -1 },
  lastActivity: { type: Date, default: Date.now, required: true, index: -1 },
  ownerType: { type: String, required: true },
  owner: { type: Schema.ObjectId, required: true, index: 1, refPath: 'ownerType' },
  name: { type: String, required: true, maxlength: 100 },
  description: { type: String, maxlength: 500 },
  policy: { type: String },
  latestMessage: { type: Schema.ObjectId, ref: 'ChatMessage' },
  visibility: { type: String, enum: ROOM_VISIBILITY_LIST, default: 'public', required: true, index: 1 },
  membershipPolicy: { type: String, enum: ROOM_MEMBERSHIP_POICY_LIST, default: 'open', required: true, index: 1 },
  members: { type: [RoomMemberSchema], default: [ ], required: true },
});

ChatRoomSchema.index({
  visibility: 1,
  membershipPolicy: 1,
}, {
  partialFilterExpression: {
    visibility: 'public',
    membershipPolicy: 'open',
  },
  name: 'chatroom_public_open_idx',
});

module.exports = mongoose.model('ChatRoom', ChatRoomSchema);