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

export interface IProductImage extends Document {
  productColor: mongoose.Types.ObjectId;
  product: mongoose.Types.ObjectId;
  imageUrl: string;
  altText?: string;
  sortOrder: number;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const ProductImageSchema: Schema = new Schema({
  productColor: {
    type: Schema.Types.ObjectId,
    ref: 'ProductColor',
    required: [true, 'Product Color is required']
  },
  product: {
    type: Schema.Types.ObjectId,
    ref: 'Product',
    required: [true, 'Product is required']
  },
  imageUrl: {
    type: String,
    required: [true, 'Image URL is required'],
    validate: {
      validator: function(v: string) {
        return /^https?:\/\/.+/.test(v) || v.startsWith('/');
      },
      message: 'Image URL must be a valid URL or relative path'
    }
  },
  altText: {
    type: String,
    maxlength: [200, 'Alt text cannot exceed 200 characters']
  },
  sortOrder: {
    type: Number,
    default: 0
  },
  isActive: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

// Indexes for better performance
ProductImageSchema.index({ productColor: 1 });
ProductImageSchema.index({ product: 1 });
ProductImageSchema.index({ productColor: 1, sortOrder: 1 });

export default mongoose.models.ProductImage || mongoose.model('ProductImage', ProductImageSchema);
