import mongoose from 'mongoose';

const saleItemSchema = new mongoose.Schema(
  {
    product: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Product',
    },
    productName: { type: String },
    quantity: { type: Number },
    price: { type: Number },
    discount: { type: Number, default: 0 },
    total: { type: Number },
    size: { type: String, default: null },
    variant: { type: String, default: '' },
    variantLabel: { type: String, default: '' },
    sellingUnit: { type: String, default: 'pcs' },
    measurement: { type: String, default: '' },
    sku: { type: String, default: '' },
    barcode: { type: String, default: '' },
    costPrice: { type: Number, default: null },
  },
  { _id: false }
);

const saleSchema = new mongoose.Schema(
  {
    billNumber: {
      type: String,
      required: [true, 'Bill number is required'],
      unique: true,
      index: true,
    },
    items: [saleItemSchema],
    subtotal: {
      type: Number,
      required: [true, 'Subtotal is required'],
    },
    discount: {
      type: Number,
      default: 0,
    },
    grandTotal: {
      type: Number,
      required: [true, 'Grand total is required'],
    },
    paymentMethod: {
      type: String,
      enum: ['CASH', 'UPI', 'CARD'],
      default: 'CASH',
    },
    customerName: {
      type: String,
      default: '',
      trim: true,
      maxlength: [120, 'Customer name cannot exceed 120 characters'],
    },
    customerPhone: {
      type: String,
      default: '',
      trim: true,
      maxlength: [20, 'Customer phone cannot exceed 20 characters'],
    },
    amountReceived: {
      type: Number,
      default: null,
      min: [0, 'Amount received cannot be negative'],
    },
    changeDue: {
      type: Number,
      default: null,
      min: [0, 'Change cannot be negative'],
    },
    returnedAmount: {
      type: Number,
      default: 0,
      min: 0,
    },
    cashier: {
      id: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin', default: null },
      name: { type: String, default: '' },
    },
    register: { type: String, default: '' },
    shiftId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Shift',
      default: null,
      index: true,
    },
  },
  { timestamps: true }
);

export default mongoose.model('Sale', saleSchema);
