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

// Slider Interface
export interface ISlider extends Document {
  title: string;
  sub_title: string;
  description: string;
  image: string;
  link?: string;
  button_text?: string;
  order: number;
  status: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const SliderSchema = new Schema<ISlider>(
  {
    // Title
    title: {
      type: String,
      required: [true, 'Slider title is required'],
      trim: true,
    },

    // Sub Title
    sub_title: {
      type: String,
      required: [true, 'Slider sub title is required'],
      trim: true,
    },

    // Description (HTML from editor)
    description: {
      type: String,
      required: [true, 'Slider description is required'],
      trim: true,
    },

    // Slider Image
    image: {
      type: String,
      required: [true, 'Slider image is required'],
      trim: true,
    },

    // Optional Link
    link: {
      type: String,
      default: '',
      trim: true,
    },

    // Button Text
    button_text: {
      type: String,
      default: 'Learn More',
      trim: true,
    },

    // Slider Order
    order: {
      type: Number,
      default: 0,
      min: 0,
    },

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

// Search Index
SliderSchema.index({
  title: 'text',
  sub_title: 'text',
  description: 'text',
});

// Trim strings before save

SliderSchema.pre('save', function () {
  if (this.title) this.title = this.title.trim();

  if (this.sub_title) {
    this.sub_title = this.sub_title.trim();
  }

  if (this.description) {
    this.description = this.description.trim();
  }

  if (this.link) {
    this.link = this.link.trim();
  }

  if (this.button_text) {
    this.button_text = this.button_text.trim();
  }

  if (this.image) {
    this.image = this.image.trim();
  }
});

export default mongoose.models.Slider ||
mongoose.model<ISlider>('Slider', SliderSchema);