// models/ProductSKU.ts
import { Decimal128 } from 'mongodb';
import mongoose, { Document, Schema } from 'mongoose';

export interface IProductSKU extends Document {
  product: mongoose.Types.ObjectId;
  sku: string;
  color: mongoose.Types.ObjectId;
  size: mongoose.Types.ObjectId;
  quantity: number;
  price: number;
  comparePrice?: number;
  createdAt: Date;
  updatedAt: Date;
}

const ProductSKUSchema: Schema = new Schema({
  product: {
    type: Schema.Types.ObjectId,
    ref: 'Product',
    required: [true, 'Product ID is required'],
    index: true
  },
  sku: {
    type: String,
    required: [true, 'SKU is required'],
    unique: true,
    trim: true,
    uppercase: true,
    index: true
  },
  color: {
    type: Schema.Types.ObjectId,
    ref: 'Color',
    required: [true, 'Color is required'],
    index: true
  },
  size: {
    type: Schema.Types.ObjectId,
    ref: 'Size',
    required: [true, 'Size is required'],
    index: true
  },
  quantity: {
    type: Number,
    required: [true, 'Quantity is required'],
    min: [0, 'Quantity cannot be negative'],
    default: 0
  },
  price: {
    type: Decimal128,
    required: [true, 'Price is required'],
    min: [0, 'Price cannot be negative']
  },
  comparePrice: {
    type: Decimal128,
    min: [0, 'Compare price cannot be negative']
  }
}, {
  timestamps: true
});

ProductSKUSchema.virtual('availableQuantity').get(function() {
  return this.quantity;
});

ProductSKUSchema.index({ product: 1, color: 1, size: 1 }, { unique: true });

export default mongoose.models.ProductSKU || mongoose.model<IProductSKU>('ProductSKU', ProductSKUSchema);