const mongoose = require('mongoose');

const refundSchema = new mongoose.Schema({
  refundId: {
    type: String,
    required: true,
    unique: true,
    uppercase: true,
    default: () => `REF-${Date.now()}`
  },
  order: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Order',
    required: true
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  return: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Return'
  },
  amount: {
    type: Number,
    required: true,
    min: 0
  },
  status: {
    type: String,
    enum: ['pending', 'processing', 'completed', 'failed'],
    default: 'pending'
  },
  method: {
    type: String,
    required: true,
    enum: ['credit_card', 'debit_card', 'paypal', 'bank_transfer', 'store_credit', 'wallet'],
    default: 'credit_card'
  },
  transactionId: {
    type: String,
    sparse: true
  },
  notes: String,
  processedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  failureReason: String
}, { 
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Add text index for search
refundSchema.index({
  'refundId': 'text',
  'order.orderNumber': 'text',
  'user.name': 'text',
  'user.email': 'text',
  'transactionId': 'text'
});

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

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

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

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

// Static method to get refunds by status
refundSchema.statics.findByStatus = function(status) {
  return this.find({ status })
    .populate('order', 'orderNumber')
    .populate('user', 'name email');
};

module.exports = mongoose.model('Refund', refundSchema);
