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

const CommentDataSchema = new Schema(
	{
		user: {
			type: Types.ObjectId,
      ref: 'User',
		},
		text: String
	},
	{ versionKey: false, _id: false }
)

export interface ICommentData {
  user?: Types.ObjectId
	text?: string
}

const CommentSchema = new Schema(
	{
		user: {
			type: Types.ObjectId,
      ref: 'User',
			required: true,
		},
		reel: {
			type: Types.ObjectId,
      ref: 'Reel',
			required: true
		},
		parent: {
			type: Types.ObjectId,
      ref: 'Comment',
		},
		data: {
			type: [CommentDataSchema],
			required: true
		},
		superLike: {
			type: Types.ObjectId,
			ref: 'SuperLike'
		},
		likes: {
			type: Number,
			default: 0
		},
		isKind: Boolean,
		isThankyou: Boolean,
		isNegative: Boolean,
	},
	{ versionKey: false, timestamps: true }
)

CommentSchema.index({ superLike: -1, likes: -1, createdAt: -1 })
CommentSchema.index({ reel: 1, parent: 1, superLike: -1, likes: -1, createdAt: -1 })
CommentSchema.index({ parent: 1 })
CommentSchema.index({ reel: 1 })

export interface IComment extends Document {
	_id: Types.ObjectId
	user: Types.ObjectId
	reel: Types.ObjectId
	parent?: Types.ObjectId
	data: ICommentData[]
	superLike?: Types.ObjectId
	likes: number
	isKind?: boolean
	isThankyou?: boolean
	isNegative?: boolean
	createdAt: Date
	updatedAt: Date
}

export const Comment = model('Comment', CommentSchema, 'comments')
