import mongoose from 'mongoose';

const commentSchema = new mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  name: String,
  text: { type: String, required: true },
  createdAt: { type: Date, default: Date.now }
});

const blogSchema = new mongoose.Schema({
  projectId: { type: String, required: true, index: true },
  title: { type: String, required: true },
  slug: { type: String, required: true, unique: false },
  description: { type: String, required: true },
  imageUrl: String,
  bigImageUrl: String, // ✅ New field
  category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
  tags: [String],
  comments: [commentSchema],
  likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, { timestamps: true });

// 👇 projectId + slug combo unique
blogSchema.index({ projectId: 1, slug: 1 }, { unique: true });

// 👇 Add base URL when converting to JSON
blogSchema.set('toJSON', {
  transform: (doc, ret) => {
    const baseUrl = process.env.BACKEND_URL || 'http://localhost:3010';
    if (ret.imageUrl && !ret.imageUrl.startsWith('http')) {
      ret.imageUrl = `${baseUrl}${ret.imageUrl}`;
    }
    if (ret.bigImageUrl && !ret.bigImageUrl.startsWith('http')) {
      ret.bigImageUrl = `${baseUrl}${ret.bigImageUrl}`;
    }
    return ret;
  }
});

export default mongoose.model('Blog', blogSchema);
