/**
 * Feature Request Model
 *
 * Stores feature requests submitted by users.
 * Users can submit, edit (if pending), and withdraw (if pending) requests.
 * Super Admins can approve, reject, mark as done, and delete requests.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type FeatureRequestStatus = 'Pending' | 'Approved' | 'Rejected' | 'Done' | 'Withdrawn';
export type FeatureRequestPriority = 'Low' | 'Medium' | 'High';
export type FeatureRequestCategory = 'UI' | 'AI' | 'Integration' | 'Other';

export interface IFeatureRequest extends Document {
  title: string;
  description: string;
  category: FeatureRequestCategory;
  priority: FeatureRequestPriority;
  status: FeatureRequestStatus;
  companyId: string;
  userId: string;
  adminNote?: string;
  isRead: boolean;
  isEdited: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const FeatureRequestSchema = new Schema<IFeatureRequest>({
  title: {
    type: String,
    required: [true, 'Title is required'],
    trim: true,
    maxlength: [200, 'Title cannot exceed 200 characters']
  },
  description: {
    type: String,
    required: [true, 'Description is required'],
    maxlength: [5000, 'Description cannot exceed 5000 characters']
  },
  category: {
    type: String,
    enum: ['UI', 'AI', 'Integration', 'Other'],
    default: 'Other'
  },
  priority: {
    type: String,
    enum: ['Low', 'Medium', 'High'],
    default: 'Medium'
  },
  status: {
    type: String,
    enum: ['Pending', 'Approved', 'Rejected', 'Done', 'Withdrawn'],
    default: 'Pending'
  },
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  userId: {
    type: String,
    required: [true, 'User ID is required'],
    index: true
  },
  adminNote: {
    type: String,
    maxlength: [1000, 'Admin note cannot exceed 1000 characters']
  },
  // Read status for Super Admin. New/modified requests are Unread (false)
  // until a Super Admin opens/views them, at which point they become Read (true).
  isRead: {
    type: Boolean,
    default: false,
    index: true
  },
  // Set true once an Admin edits the request, so the Super Admin can see
  // at a glance that the entry was modified after submission.
  isEdited: {
    type: Boolean,
    default: false,
    index: true
  }
}, {
  timestamps: true
});

// Compound indexes for efficient queries
FeatureRequestSchema.index({ companyId: 1, status: 1 });
FeatureRequestSchema.index({ companyId: 1, userId: 1 });
FeatureRequestSchema.index({ status: 1, createdAt: -1 });

export const FeatureRequest = mongoose.models.FeatureRequest || mongoose.model<IFeatureRequest>('FeatureRequest', FeatureRequestSchema);