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

export interface IEmailTemplate extends Document {
  _id: mongoose.Types.ObjectId;
  name: string;
  slug: string;
  subject: string;
  content: string;
  description?: string;
  fromName: string;
  fromEmail: string;
  ccEmail?: string;
  createdAt: Date;
  updatedAt: Date;
}

function makeSlug(text: string) {
  return text
    .toString()
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/--+/g, '-');
}

const EmailTemplateSchema = new Schema<IEmailTemplate>(
  {
    name: {
      type: String,
      required: [true, 'Name is required'],
      trim: true,
      maxlength: [200, 'Name cannot exceed 200 characters'],
    },
    slug: {
      type: String,
      unique: true,
      trim: true,
      lowercase: true,
    },
    subject: {
      type: String,
      required: [true, 'Subject is required'],
      trim: true,
      maxlength: [500, 'Subject cannot exceed 500 characters'],
    },
    content: {
      type: String,
      required: [true, 'Content is required'],
    },
    description: {
      type: String,
      trim: true,
    },
    fromName: {
      type: String,
      required: [true, 'From name is required'],
      trim: true,
    },
    fromEmail: {
      type: String,
      required: [true, 'From email is required'],
      trim: true,
      lowercase: true,
      match: [/^\S+@\S+\.\S+$/, 'Please use a valid email address'],
    },
    ccEmail: {
      type: String,
      trim: true,
      lowercase: true,
      default: '',
    },
  },
  { timestamps: true }
);

// Auto-generate slug from name
EmailTemplateSchema.pre('save', function () {
  if (this.isModified('name') || !this.slug) {
    this.slug = makeSlug(this.name as string);
  }
});

EmailTemplateSchema.index({ slug: 1 }, { unique: true });

export default mongoose.models.EmailTemplate ||
  mongoose.model<IEmailTemplate>('EmailTemplate', EmailTemplateSchema);