const Blog = require("../models/blogModel");
const APIFeatures = require("../utils/ApiFeatures"); // Assuming you have this util
const {
  deleteOldBlogImage,
} = require("../storage/middlewareStorage/uploadBlogMedia");

// 1. Get All Blogs
exports.getAllBlogs = async (req, res) => {
  try {
    // Allow filtering (e.g. ?category=News&isPublished=true)
    const features = new APIFeatures(Blog.find(), req.query)
      .filter()
      .sort()
      .limitFields()
      .paginate();

    const blogs = await features.query;

    res.status(200).json({
      status: "success",
      results: blogs.length,
      data: { blogs },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 2. Get Single Blog (by ID or Slug logic if preferred)
exports.getBlog = async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);

    if (!blog) {
      return res
        .status(404)
        .json({ status: "fail", message: "Blog not found" });
    }

    // Optional: Increment view count
    blog.views += 1;
    await blog.save({ validateBeforeSave: false });

    res.status(200).json({ status: "success", data: { blog } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 3. Create Blog
exports.createBlog = async (req, res) => {
  try {
    // 1. Handle Image
    if (req.file) {
      req.body.coverImage = req.file.filename;
    }

    // 2. Set Author to current logged-in user
    if (!req.body.author) {
      req.body.author = req.user.id;
    }

    const newBlog = await Blog.create(req.body);

    res.status(201).json({ status: "success", data: { blog: newBlog } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 4. Update Blog
exports.updateBlog = async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);
    if (!blog) return res.status(404).json({ message: "Blog not found" });

    // Handle Image Update
    if (req.file) {
      await deleteOldBlogImage(blog.coverImage); // Delete old
      req.body.coverImage = req.file.filename; // Set new
    }

    // If title is updated, slugify will handle it in pre-save,
    // BUT findByIdAndUpdate doesn't trigger save middleware unless configured.
    // Instead, we pass the data.
    const updatedBlog = await Blog.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true,
    });

    res.status(200).json({ status: "success", data: { blog: updatedBlog } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 5. Delete Blog
exports.deleteBlog = async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);
    if (!blog) return res.status(404).json({ message: "Blog not found" });

    // Delete image from server
    await deleteOldBlogImage(blog.coverImage);

    // Delete from DB
    await Blog.findByIdAndDelete(req.params.id);

    res.status(204).json({ status: "success", data: null });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
