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

const MessageFileSchema = new Schema({
	url: {
		type: String,
		required: true
	},
	cover: String,
	meta: Object
}, { versionKey: false })

export interface IMessageFile {
	_id: Types.ObjectId
	url: string
	cover?: string
	meta?: any
}

const MessageSchema = new Schema(
	{
		user: {
			type: Types.ObjectId,
			ref: 'User',
			required: true,
		},
		chat: {
			type: Types.ObjectId,
			ref: 'Chat',
			required: true
		},
		reel: {
			type: Types.ObjectId,
			ref: 'Reel',
		},
		content: String,
		files: {
			type: [MessageFileSchema],
			default: undefined
		},
		tag: String,
		at: {
			type: Date,
			default: Date
		}
	},
	{ versionKey: false }
)

MessageSchema.index({ chat: 1, at: 1 })
MessageSchema.index({ chat: 1, at: -1 })

export interface IMessage extends Document {
	_id: Types.ObjectId
	user: Types.ObjectId
	chat: Types.ObjectId
	reel?: Types.ObjectId
	content?: string
	files?: IMessageFile[]
	tag?: string
	at: Date
}

export const Message = model('Message', MessageSchema, 'messages')
