import { Schema, model, Document, Types } from 'mongoose'

const ChatTagSchema = new Schema(
	{
		tag: {
			type: String,
			required: true
		},
		label: {
			type: String,
			required: true
		}
	},
	{ versionKey: false, _id: false }
)

export interface IChatTag {
	tag: string
	label: string
}

const ChatParticipantSchema = new Schema(
	{
		user: {
			type: Types.ObjectId,
			ref: 'User',
			required: true
		},
		isAdmin: Boolean,
		status: {
			type: String,
			enum: ['accepted', 'rejected']
		},
		lastReadAt: {
			type: Date,
			default: Date
		}
	},
	{ versionKey: false }
)

export interface IChatParticipant {
	_id: Types.ObjectId
	user: Types.ObjectId
	isAdmin?: boolean
	status?: 'accepted' | 'rejected'
	lastReadAt: Date
}

const ChatSchema = new Schema(
	{
		creator: {
			type: Types.ObjectId,
			ref: 'User',
			required: true,
		},
		user: {
			type: Types.ObjectId,
			ref: 'User'
		},
		isGroup: Boolean,
		category: String,
		meetMe: {
			type: Types.ObjectId,
			ref: 'Connection'
		},
		event: {
			type: Types.ObjectId,
			ref: 'Event'
		},
		lastMessage: {
			type: Types.ObjectId,
			ref: 'Message'
		},
		blocked: Boolean,
		name: String,
		photo: String,
		allowPublicPost: {
			type: Boolean,
			required: false,
			default: true
		},
		tags: {
			type: [ChatTagSchema],
			default: [
				{tag: 'exams', label: 'Exams'},
				{tag: 'lectures', label: 'Lectures & Summaries'},
			]
		},
		participants: {
			type: [ChatParticipantSchema],
			required: true
		},
		restricted: Boolean
	},
	{ versionKey: false, timestamps: true }
)

ChatSchema.index({ 'participants.user': 1, updatedAt: -1 })

ChatSchema.index(
  { meetMe: 1 },
  { partialFilterExpression: { meetMe: { $exists: true } } }
)

ChatSchema.index(
  { isGroup: 1, updatedAt: -1 },
  { partialFilterExpression: { isGroup: true } }
)

export interface IChat extends Document {
	_id: Types.ObjectId
	creator: Types.ObjectId
	user?: Types.ObjectId
	isGroup?: Boolean
	category?: string
	meetMe?: Types.ObjectId  // connection
	event?: Types.ObjectId
	lastMessage?: Types.ObjectId
	blocked?: boolean
	name?: string
	photo?: string
	allowPublicPost?: boolean
	tags: IChatTag[]
	participants: IChatParticipant[]
	restricted?: boolean
	createdAt: Date
	updatedAt: Date
}

export const Chat = model('Chat', ChatSchema, 'chats')
