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

export interface INewsletter extends Document {
  _id: mongoose.Types.ObjectId;
  email: string;
  status: 'active' | 'inactive';
  subscribedAt: Date;
  createdAt: Date;
  updatedAt: Date;
}

const NewsletterSchema = new Schema<INewsletter>(
  {
    email: {
      type: String,
      required: [true, 'Email is required'],
      unique: true,
      trim: true,
      lowercase: true,
      match: [/^\S+@\S+\.\S+$/, 'Please use a valid email address'],
    },
    status: {
      type: String,
      enum: ['active', 'inactive'],
      default: 'active',
    },
    subscribedAt: {
      type: Date,
      default: Date.now,
    },
  },
  { timestamps: true }
);

NewsletterSchema.index({ email: 1 }, { unique: true });
NewsletterSchema.index({ status: 1 });

export default mongoose.models.Newsletter ||
  mongoose.model<INewsletter>('Newsletter', NewsletterSchema);