import mongoose, { Document, Schema } from 'mongoose';

export interface IReview extends Document {
  _id: mongoose.Types.ObjectId;
  product: mongoose.Types.ObjectId;

  authorName: string;
  authorEmail: string;
  reviewTitle: string;
  reviewDescription: string;
  rating: number;
  images: string[];
  status: 'not-approved' | 'approved' | 'rejected';
  createdAt: Date;
  updatedAt: Date;
}

const ReviewSchema = new Schema<IReview>(
  {
    product: {
      type: Schema.Types.ObjectId,
      ref: 'Product',
      required: [true, 'Product is required'],
    },
    authorName: {
      type: String,
      required: [true, 'Author name is required'],
      trim: true,
      maxlength: [100, 'Author name cannot exceed 100 characters'],
    },
    authorEmail: {
      type: String,
      required: [true, 'Author email is required'],
      trim: true,
      lowercase: true,
    },
    reviewTitle: {
      type: String,
      required: [true, 'Review title is required'],
      trim: true,
      maxlength: [200, 'Review title cannot exceed 200 characters'],
    },
    reviewDescription: {
      type: String,
      trim: true,
      maxlength: [2000, 'Review description cannot exceed 2000 characters'],
    },
    rating: {
      type: Number,
      required: [true, 'Rating is required'],
      min: [1, 'Rating must be at least 1'],
      max: [5, 'Rating cannot exceed 5'],
    },
    images: {
      type: [String],
      default: [],
    },
    status: {
      type: String,
      enum: ['not-approved', 'approved'],
      default: 'not-approved',
    },
  },
  { timestamps: true }
);

ReviewSchema.index({ product: 1 });
ReviewSchema.index({ status: 1 });
ReviewSchema.index({ rating: 1 });

export default mongoose.models.Review ||
  mongoose.model<IReview>('Review', ReviewSchema);