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

export interface IBanner extends Document {
  banner_title: string;
  banner_slug: string;
  banner_description?: string;
  banner_image: string; // Path to stored image file
  status: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const BannerSchema: Schema = new Schema(
  {
    banner_title: {
      type: String,
      required: [true, 'Banner title is required'],
      trim: true,
      maxlength: [200, 'Banner title cannot exceed 200 characters']
    },

    banner_slug: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      lowercase: true
    },

    banner_description: {
      type: String,
      trim: true,
      maxlength: [1000, 'Banner description cannot exceed 1000 characters']
    },

    banner_image: {
      type: String,
      required: [true, 'Banner image is required'],
      trim: true
    },

    status: {
      type: Boolean,
      default: true
    }
  },
  {
    timestamps: true
  }
);

// ✅ Indexes
BannerSchema.index({ status: 1 });
BannerSchema.index({ banner_slug: 1 });

// ✅ Pre-save middleware to generate slug
BannerSchema.pre('save', function(this: IBanner) {
  if (this.isModified('banner_title') && !this.banner_slug) {
    this.banner_slug = this.banner_title
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/--+/g, '-');
  }
});

export default mongoose.models.Banner || mongoose.model<IBanner>('Banner', BannerSchema);