// Connections
import mongoConnection from "$connections/mongo/mongo.connection.js";

import mongoose from "mongoose";
const mongooseSchema = mongoose.Schema;

export const MANUAL_NEWS_AUTHORS = [
  "علی پازکی",
  "محمد غواصی کناری",
  "حسین صیادلو",
  "علی حیدری",
  "میرسجاد مسجد موسوی",
  "اسماعیل ثروتی",
  "میثم امیری پریان",
  "متین عبدی",
  "عباس ابراهیمی",
  "عباس دادرس",
  "محمدرضا رافع",
  "همایون نسیمی",
];

const normalizeAuthorReference = (value) => {
  if (!value) return null;

  const candidate =
    typeof value === "object" && value !== null && value._id ? value._id : value;

  return mongoose.isValidObjectId(candidate) ? candidate : null;
};

export const schemaModel = {
  title: {
    type: String,
    required: true,
    trim: true,
    index: true,
  },
  slug: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    index: true,
    match: [/^\d{6}$/, "slug must be a unique 6 digit number"],
  },
  category: {
    type: String,
    required: true,
    trim: true,
    lowercase: true,
    index: true,
  },
  excerpt: {
    type: String,
    default: "",
    trim: true,
  },
  content: {
    type: String,
    required: true,
  },
  coverImage: {
    type: mongooseSchema.Types.ObjectId,
    ref: "File",
    default: null,
  },
  author: {
    type: mongooseSchema.Types.ObjectId,
    ref: "User",
    default: null,
    index: true,
    set: normalizeAuthorReference,
  },
  authorName: {
    type: String,
    default: "",
    trim: true,
    enum: ["", ...MANUAL_NEWS_AUTHORS],
  },
  tags: {
    type: [String],
    default: [],
  },
  isFeatured: {
    type: Boolean,
    default: false,
    index: true,
  },
  isActive: {
    type: Boolean,
    default: true,
    index: true,
  },
  seoTitle: {
    type: String,
    default: "",
    trim: true,
  },
  seoDescription: {
    type: String,
    default: "",
    trim: true,
  },
  viewCount: {
    type: Number,
    default: 0,
    min: 0,
  },
};

export const schema = new mongooseSchema(schemaModel, { timestamps: true });

schema.index({ title: "text", excerpt: "text", content: "text", tags: "text" });
schema.index({ isActive: 1, createdAt: -1 });
schema.index({ category: 1, isActive: 1, createdAt: -1 });

schema.pre("validate", function (next) {
  if (this.slug) {
    this.slug = this.slug.trim();
  }

  if (this.category) {
    this.category = this.category.trim().toLowerCase();
  }

  if (Array.isArray(this.tags)) {
    this.tags = this.tags
      .map((tag) => (typeof tag === "string" ? tag.trim() : ""))
      .filter(Boolean);
  }

  if (typeof this.authorName === "string") {
    this.authorName = this.authorName.trim();
  }

  next();
});

export default mongoConnection.model("News", schema);
