import mongoose from "mongoose";
import logger from "../utils/logger.js";

const projectSchema = new mongoose.Schema(
  {
    srNo: {
      type: Number,
      unique: true,
      required: false, // Auto-generated in pre-save hook, not required in schema
      index: true,
    },
    title: {
      en: {
        type: String,
        required: [true, "English title is required"],
        trim: true,
        maxlength: [300, "English title cannot exceed 300 characters"],
      },
      ar: {
        type: String,
        required: [true, "Arabic title is required"],
        trim: true,
        maxlength: [300, "Arabic title cannot exceed 300 characters"],
      },
    },
    description: {
      en: {
        type: String,
        required: [true, "English description is required"],
        trim: true,
        maxlength: [5000, "English description cannot exceed 5000 characters"],
      },
      ar: {
        type: String,
        required: [true, "Arabic description is required"],
        trim: true,
        maxlength: [5000, "Arabic description cannot exceed 5000 characters"],
      },
    },
    images: {
      type: [
        {
          url: {
            type: String,
            required: true,
          },
          filename: {
            type: String,
            required: true,
          },
        },
      ],
      default: [],
      validate: {
        validator: function (images) {
          return images.length <= 10;
        },
        message: "Maximum 10 images allowed per project",
      },
    },
    featuredOnHomepage: {
      type: Boolean,
      default: false,
    },
    status: {
      type: String,
      enum: ["draft", "published"],
      default: "draft",
    },
    createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Admin",
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

// Auto-generate sequential number before saving
projectSchema.pre("save", async function (next) {
  // Only generate srNo for new documents that don't have one
  if (
    this.isNew &&
    (!this.srNo || this.srNo === null || this.srNo === undefined)
  ) {
    try {
      // Find the highest srNo
      const lastProject = await mongoose
        .model("Project")
        .findOne()
        .sort({ srNo: -1 })
        .select("srNo")
        .lean();

      // Set srNo to the next number (start from 1 if no projects exist)
      this.srNo = lastProject && lastProject.srNo ? lastProject.srNo + 1 : 1;
    } catch (error) {
      // If query fails, default to 1 to ensure srNo is always set
      // Log the error but don't fail the save operation
      logger.warn(
        "Failed to auto-generate srNo, using default value of 1",
        error
      );
      this.srNo = 1;
    }
  }
  next();
});

// Index for featured projects
projectSchema.index({ featuredOnHomepage: 1, status: 1 });
projectSchema.index({ status: 1 });

// Text indexes for search functionality (searches both English and Arabic titles)
projectSchema.index({ "title.en": "text", "title.ar": "text" });
projectSchema.index({ "title.en": 1 }); // Regular index for regex searches
projectSchema.index({ "title.ar": 1 }); // Regular index for regex searches

const Project = mongoose.model("Project", projectSchema);

export default Project;
