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

export interface IColor extends Document {
  name: string;
  hexCode: string;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const ColorSchema: Schema = new Schema({
  name: {
    type: String,
    required: [true, 'Color name is required'],
    trim: true,
    maxlength: [50, 'Color name cannot exceed 50 characters']
  },
  hexCode: {
    type: String,
    required: [true, 'Hex code is required'],
    validate: {
      validator: function(v: string) {
        return /^#[0-9A-F]{6}$/i.test(v);
      },
      message: 'Hex code must be in format #RRGGBB'
    }
  },
  isActive: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

// Index for better performance
ColorSchema.index({ name: 1 });
ColorSchema.index({ hexCode: 1 });

// Ensure unique combination of name and hexCode
ColorSchema.index({ name: 1, hexCode: 1 }, { unique: true });

export default mongoose.models.Color || mongoose.model<IColor>('Color', ColorSchema);