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

export interface ILocalizedString {
  en: string;
  zh: string;
}

const localizedStringSchema = {
  en: { type: String, default: '' },
  zh: { type: String, default: '' },
};

const localizedStringRequired = {
  en: { type: String, required: true },
  zh: { type: String, default: '' },
};

export interface IService extends Document {
  title: ILocalizedString;
  slug: string;
  shortDescription: ILocalizedString;
  fullDescription: ILocalizedString;
  icon?: string;
  featuredImage?: string;
  link?: string;
  features: ILocalizedString[];
  order: number;
  status: 'active' | 'inactive';
  seo: {
    title?: string;
    description?: string;
    keywords?: string[];
  };
  createdAt: Date;
  updatedAt: Date;
}

const serviceSchema = new Schema<IService>(
  {
    title: {
      type: localizedStringRequired,
      required: true,
    },
    slug: {
      type: String,
      unique: true,
      lowercase: true,
    },
    shortDescription: {
      type: localizedStringRequired,
      required: true,
    },
    fullDescription: {
      type: localizedStringRequired,
      required: true,
    },
    icon: String,
    featuredImage: String,
    link: String,
    features: [{
      type: localizedStringSchema,
    }],
    order: {
      type: Number,
      default: 0,
    },
    status: {
      type: String,
      enum: ['active', 'inactive'],
      default: 'active',
    },
    seo: {
      title: String,
      description: String,
      keywords: [String],
    },
  },
  {
    timestamps: true,
  }
);

serviceSchema.pre('save', function () {
  if (this.isModified('title') && !this.slug) {
    const enTitle = typeof this.title === 'object' ? this.title.en : this.title;
    this.slug = slugify(enTitle || '', { lower: true, strict: true });
  }
});

serviceSchema.index({ status: 1, order: 1 });

export const Service = mongoose.model<IService>('Service', serviceSchema);
