/**
 * Feature Request Comment Model
 *
 * Threaded comments on a feature request. Any participant with access to the
 * request (the requesting user, company Admins, and Super Admins) can post
 * comments and reply to existing comments to build a threaded discussion.
 *
 * Threading is modelled with a nullable `parentId` — a top-level comment has
 * `parentId = null`; a reply points at the comment it answers.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IFeatureRequestComment extends Document {
  featureRequestId: string;
  parentId: string | null;
  companyId: string;
  userId: string;
  userName: string;
  userRole: string;
  content: string;
  createdAt: Date;
  updatedAt: Date;
}

const FeatureRequestCommentSchema = new Schema<IFeatureRequestComment>({
  featureRequestId: {
    type: String,
    required: [true, 'Feature request ID is required'],
    index: true
  },
  parentId: {
    type: String,
    default: null,
    index: true
  },
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  userId: {
    type: String,
    required: [true, 'User ID is required'],
    index: true
  },
  // Author info denormalised at creation time for simple rendering.
  userName: {
    type: String,
    required: true,
    default: 'Unknown'
  },
  userRole: {
    type: String,
    default: 'user'
  },
  content: {
    type: String,
    required: [true, 'Comment content is required'],
    trim: true,
    maxlength: [2000, 'Comment cannot exceed 2000 characters']
  }
}, {
  timestamps: true
});

// Efficient lookup of a request's thread in chronological order
FeatureRequestCommentSchema.index({ featureRequestId: 1, createdAt: 1 });

export const FeatureRequestComment =
  mongoose.models.FeatureRequestComment ||
  mongoose.model<IFeatureRequestComment>('FeatureRequestComment', FeatureRequestCommentSchema);
