const mongoose = require('mongoose');

const returnSchema = new mongoose.Schema({
  returnId: {
    type: String,
    required: true,
    unique: true,
    uppercase: true,
    default: () => `RET-${Date.now()}`
  },
  order: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Order',
    required: true
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  reason: {
    type: String,
    required: true
  },
  status: {
    type: String,
    enum: ['pending', 'approved', 'rejected', 'processing', 'completed'],
    default: 'pending'
  },
  amount: {
    type: Number,
    required: true
  },
  items: [
    {
      _id: false,
      product: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Item',
        required: true
      },
      name: {
        type: String,
        required: true
      },
      quantity: {
        type: Number,
        required: true,
        min: 1
      },
      price: {
        type: Number,
        required: true,
        min: 0
      }
    }
  ],
  notes: String,
  refundMethod: {
    type: String,
    enum: ['original_payment', 'store_credit', 'bank_transfer'],
    default: 'original_payment'
  },
  processedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, { 
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Add text index for search
returnSchema.index({
  'returnId': 'text',
  'order.orderNumber': 'text',
  'user.name': 'text',
  'user.email': 'text',
  'reason': 'text'
});

// Virtual for order number
returnSchema.virtual('orderNumber', {
  ref: 'Order',
  localField: 'order',
  foreignField: '_id',
  justOne: true
});

// Virtual for user details
returnSchema.virtual('userDetails', {
  ref: 'User',
  localField: 'user',
  foreignField: '_id',
  justOne: true,
  options: { select: 'name email phone' }
});

// Pre-save hook to generate returnId if not provided
returnSchema.pre('save', function(next) {
  if (!this.returnId) {
    this.returnId = `RET-${Date.now()}`;
  }
  next();
});

// Static method to get return by ID with populated fields
returnSchema.statics.findByIdWithDetails = async function(id) {
  return this.findById(id)
    .populate('order', 'orderNumber')
    .populate('user', 'name email')
    .populate('items.product', 'name price');
};

module.exports = mongoose.model('Return', returnSchema);
