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 IContentBlock {
  type: 'hero' | 'text' | 'image' | 'gallery' | 'video' | 'cta' | 'stats' | 'testimonials' | 'team' | 'services' | 'contact' | 'custom';
  order: number;
  data: Record<string, unknown>;
}

export interface ISeoMeta {
  title?: string;
  description?: string;
  keywords?: string[];
  ogImage?: string;
}

export interface IPage extends Document {
  title: ILocalizedString;
  slug: string;
  content: IContentBlock[];
  excerpt?: ILocalizedString;
  featuredImage?: string;
  template: 'default' | 'landing' | 'about' | 'services' | 'contact' | 'custom';
  status: 'draft' | 'published' | 'archived';
  seo: ISeoMeta;
  author: mongoose.Types.ObjectId;
  publishedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const contentBlockSchema = new Schema<IContentBlock>(
  {
    type: {
      type: String,
      enum: ['hero', 'text', 'image', 'gallery', 'video', 'cta', 'stats', 'testimonials', 'team', 'services', 'contact', 'custom'],
      required: true,
    },
    order: {
      type: Number,
      default: 0,
    },
    data: {
      type: Schema.Types.Mixed,
      default: {},
    },
  },
  { _id: false }
);

const seoMetaSchema = new Schema<ISeoMeta>(
  {
    title: String,
    description: String,
    keywords: [String],
    ogImage: String,
  },
  { _id: false }
);

const pageSchema = new Schema<IPage>(
  {
    title: {
      type: localizedStringRequired,
      required: true,
    },
    slug: {
      type: String,
      unique: true,
      lowercase: true,
    },
    content: [contentBlockSchema],
    excerpt: {
      type: localizedStringSchema,
    },
    featuredImage: String,
    template: {
      type: String,
      enum: ['default', 'landing', 'about', 'services', 'contact', 'custom'],
      default: 'default',
    },
    status: {
      type: String,
      enum: ['draft', 'published', 'archived'],
      default: 'draft',
    },
    seo: {
      type: seoMetaSchema,
      default: {},
    },
    author: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    publishedAt: Date,
  },
  {
    timestamps: true,
  }
);

pageSchema.pre('save', function () {
  if (this.isModified('title') && !this.slug) {
    const enTitle = typeof this.title === 'object' ? this.title.en : (this.title as string);
    this.slug = slugify(enTitle || '', { lower: true, strict: true });
  }
  if (this.status === 'published' && !this.publishedAt) {
    this.publishedAt = new Date();
  }
});

pageSchema.index({ status: 1, publishedAt: -1 });

export const Page = mongoose.model<IPage>('Page', pageSchema);
