import mongoose from 'mongoose';

const RETURN_REASONS = [
  'CUSTOMER_RETURN',
  'DAMAGED_PRODUCT',
  'WRONG_PRODUCT',
  'DEFECTIVE_PRODUCT',
  'EXPIRED_PRODUCT',
  'OTHER',
];
const REFUND_METHODS = ['CASH', 'UPI', 'CARD', 'STORE_CREDIT'];

const returnItemSchema = new mongoose.Schema(
  {
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
    productName: { type: String, default: '' },
    variantId: { type: String, default: '' },
    variantLabel: { type: String, default: '' },
    sku: { type: String, default: '' },
    quantity: { type: Number, required: true, min: 1 },
    price: { type: Number, required: true, min: 0 },
    amount: { type: Number, required: true, min: 0 },
    costPrice: { type: Number, default: null },
  },
  { _id: false }
);

const saleReturnSchema = new mongoose.Schema(
  {
    returnNumber: { type: String, required: true, unique: true },
    sale: { type: mongoose.Schema.Types.ObjectId, ref: 'Sale', required: true, index: true },
    billNumber: { type: String, default: '' },
    items: { type: [returnItemSchema], required: true },
    totalRefund: { type: Number, required: true, min: 0 },
    reason: { type: String, enum: RETURN_REASONS, required: true },
    refundMethod: { type: String, enum: REFUND_METHODS, default: 'CASH' },
    refundReference: { type: String, default: '', trim: true, maxlength: 60 },
    notes: { type: String, default: '', trim: true, maxlength: 500 },
    processedBy: {
      id: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
      name: { type: String, default: '' },
    },
  },
  { timestamps: true }
);

saleReturnSchema.index({ sale: 1, 'items.product': 1, 'items.variantId': 1 });

export default mongoose.model('SaleReturn', saleReturnSchema);
