import Blog from '../models/blog.model.js';
import Category from '../models/category.model.js';
import slugify from 'slugify';

// ✅ Create Blog for particular project
export const createBlog = async (req, res) => {
  try {
    const { projectId, title, description, categoryId, tags } = req.body;
    if (!projectId) return res.status(400).json({ message: 'projectId is required' });

    const slug = slugify(title, { lower: true, strict: true });

    const blog = await Blog.create({
      projectId,
      title,
      description,
      slug,
      category: categoryId,
      tags,
      imageUrl: req.files?.imageUrl ? `/uploads/${req.files.imageUrl[0].filename}` : '',
      bigImageUrl: req.files?.bigImageUrl ? `/uploads/${req.files.bigImageUrl[0].filename}` : ''
    });

    res.status(201).json(blog);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// ✅ Get All Blogs for a particular project
export const getAllBlogs = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', category, projectId } = req.query;
    if (!projectId) return res.status(400).json({ message: 'projectId is required' });

    const query = {
      projectId,
      title: { $regex: search, $options: 'i' }
    };

    if (category) {
      const cat = await Category.findOne({ slug: category });
      if (cat) query.category = cat._id;
    }

    const blogs = await Blog.find(query)
      .populate('category', 'name slug')
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(parseInt(limit));

    const total = await Blog.countDocuments(query);

    res.json({ total, page: parseInt(page), blogs });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// ✅ Get Single Blog by Slug + projectId
export const getBlogBySlug = async (req, res) => {
  try {
    const { projectId } = req.query; // 👈 query param மூலம்
    if (!projectId) return res.status(400).json({ message: 'projectId is required' });

    const blog = await Blog.findOne({ slug: req.params.slug, projectId })
      .populate('category', 'name slug');

    if (!blog) return res.status(404).json({ message: 'Blog not found' });
    res.json(blog);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// ✅ Add Comment to Blog (projectId check optional – id already unique)
export const addComment = async (req, res) => {
  try {
    const { text, name } = req.body;
    const blog = await Blog.findById(req.params.id);
    if (!blog) return res.status(404).json({ message: 'Blog not found' });

    blog.comments.push({
      user: req.user?._id,
      name: name || 'Anonymous',
      text
    });

    await blog.save();
    res.json(blog.comments);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// ✅ Like / Unlike
export const likeBlog = async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);
    if (!blog) return res.status(404).json({ message: 'Blog not found' });

    const userId = req.user._id;
    if (blog.likes.includes(userId)) blog.likes.pull(userId);
    else blog.likes.push(userId);

    await blog.save();
    res.json({ likesCount: blog.likes.length });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
