import mongoose, { Document, Schema } from 'mongoose';

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

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

// Indexes for better performance
ProductColorSchema.index({ product: 1, color: 1, size: 1 }, { unique: true });
ProductColorSchema.index({ product: 1 });
ProductColorSchema.index({ color: 1 });
ProductColorSchema.index({ size: 1 });

export default mongoose.models.ProductColor || mongoose.model('ProductColor', ProductColorSchema);
