import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { ModerationStatus } from '../../../common/enums/moderation-status.enum';
import { Post } from '../../posts/schemas/post.schema';
import { User } from '../../users/schemas/user.schema';

export type CommentDocument = HydratedDocument<Comment>;

@Schema({ timestamps: true, versionKey: false })
export class Comment {
  @Prop({ type: Types.ObjectId, ref: Post.name, required: true, index: true })
  postId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, ref: User.name, required: true, index: true })
  authorId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, required: false, index: true })
  parentCommentId?: Types.ObjectId;

  @Prop({ required: true, maxlength: 1000 })
  content!: string;

  @Prop({ type: [String], default: [] })
  mentionUsernames!: string[];

  @Prop({
    type: String,
    enum: Object.values(ModerationStatus),
    default: ModerationStatus.ACTIVE,
    index: true,
  })
  moderationStatus!: ModerationStatus;

  @Prop({ default: '', maxlength: 300 })
  moderationReason!: string;

  @Prop({ default: false, index: true })
  isDeleted!: boolean;

  @Prop({ default: false, index: true })
  isPinned!: boolean;

  @Prop({ default: false, index: true })
  hiddenByFilter!: boolean;

  @Prop({ default: '', maxlength: 120 })
  hiddenReason!: string;

  @Prop({ type: Date, default: null })
  deletedAt?: Date | null;

  @Prop({ type: Types.ObjectId, ref: User.name, default: null })
  deletedBy?: Types.ObjectId | null;
}

export const CommentSchema = SchemaFactory.createForClass(Comment);
CommentSchema.index({ postId: 1, createdAt: -1 });
CommentSchema.index({ postId: 1, parentCommentId: 1, isDeleted: 1, createdAt: -1 });
CommentSchema.index({ moderationStatus: 1, createdAt: -1 });
CommentSchema.index({ postId: 1, isPinned: -1, createdAt: -1 });
