const mongoose = require('mongoose');

const fundsTransferSchema = new mongoose.Schema(
  {
    deliveryBoy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    amount: {
      type: Number,
      required: true,
      min: 0,
    },
    date: {
      type: Date,
      default: Date.now,
    },
    transactionId: {
      type: String,
      required: true,
      unique: true,
    },
    status: {
      type: String,
      enum: ['pending', 'completed', 'failed'],
      default: 'pending',
    },
    method: {
      type: String,
      required: true,
      enum: ['bank_transfer', 'upi', 'wallet', 'other'],
    },
    notes: String,
    createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

// Indexes for better query performance
fundsTransferSchema.index({ deliveryBoy: 1, status: 1 });
fundsTransferSchema.index({ transactionId: 1 }, { unique: true });

// Generate transaction ID before validation
fundsTransferSchema.pre('validate', function (next) {
  try {
    // Check if deliveryBoy is a valid ObjectId
    if (this.deliveryBoy && !mongoose.Types.ObjectId.isValid(this.deliveryBoy)) {
      throw new Error('Invalid delivery boy ID format');
    }
    
    // Generate transaction ID if not provided
    if (!this.transactionId) {
      this.transactionId = `FT-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    }
    
    // Set the current date if not provided
    if (!this.date) {
      this.date = Date.now();
    }
    
    next();
  } catch (error) {
    next(error);
  }
});

const FundsTransfer = mongoose.model('FundsTransfer', fundsTransferSchema);

module.exports = FundsTransfer;
