const mongoose = require('mongoose');
const BaseModel = require('./BaseModel');

const bannerSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'Title is required'],
    trim: true,
    maxlength: [100, 'Title cannot be more than 100 characters']
  },
  subtitle: {
    type: String,
    trim: true,
    maxlength: [200, 'Subtitle cannot be more than 200 characters']
  },
  image: {
    type: String,
    required: [true, 'Image URL is required']
  },
  link: {
    type: String,
    trim: true
  },
  isActive: {
    type: Boolean,
    default: true
  },
  position: {
    type: Number,
    default: 0
  },
  type: {
    type: String,
    enum: ['main', 'secondary', 'promo'],
    default: 'main'
  },
  startDate: {
    type: Date,
    default: Date.now
  },
  endDate: {
    type: Date
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Indexes
bannerSchema.index({ isActive: 1, position: 1 });

// Static method to get active banners
bannerSchema.statics.getActiveBanners = async function(type = 'main') {
  const now = new Date();
  return await this.find({
    isActive: true,
    $or: [
      { startDate: { $lte: now }, endDate: { $exists: false } },
      { startDate: { $lte: now }, endDate: { $gte: now } }
    ],
    type
  })
  .sort({ position: 1, createdAt: -1 })
  .select('-__v -createdAt -updatedAt -createdBy')
  .lean();
};

// Create model
const Banner = mongoose.model('Banner', bannerSchema);

module.exports = Banner;
