const { pageBlog } = require("../../models/blogs/pageBlogModel");
const uploadDir = "uploads/page_blog_images"; // customize as needed

const PageBlogControllers = {
  createEntry: async (req, res) => {
    try {
      const { main_heading, content } = req.body;

      const data = {
        main_heading: main_heading?.trim(),
        content: content,
      };

      if (req.file) {
        data.blog_image = `/${uploadDir}/${req.file.filename}`;
      }

      const result = await pageBlog.create(data);
      if (result?.error) {
        return res.status(400).json({ success: false, message: result.error });
      }

      res.status(201).json({
        success: true,
        message: "Page blog created successfully!",
        data: result,
      });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  getAllEntries: async (req, res) => {
    try {
      const result = await pageBlog.getAll();
      if (!result.length) {
        return res.status(404).json({ success: false, message: "No entries found." });
      }

      res.status(200).json({ success: true, data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  getSingleEntry: async (req, res) => {
    try {
      const entry = await pageBlog.getSingle(req.params.id);
      if (!entry) {
        return res.status(404).json({ success: false, message: "Entry not found" });
      }
      res.status(200).json({ success: true, data: entry });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  updateEntry: async (req, res) => {
    try {
      const { main_heading, content } = req.body;

      const data = {
        main_heading: main_heading?.trim(),
        content: content,
      };

      if (req.file) {
        data.blog_image = `/${uploadDir}/${req.file.filename}`;
      }

      const updated = await pageBlog.update(req.params.id, data);
      if (!updated) {
        return res.status(404).json({ success: false, message: "Entry not found" });
      }

      res.status(200).json({ success: true, message: "Page blog updated!", data: updated });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  deleteEntry: async (req, res) => {
    try {
      const deleted = await pageBlog.delete(req.params.id);
      if (!deleted) {
        return res.status(404).json({ success: false, message: "Entry not found" });
      }
      res.status(200).json({ success: true, ...deleted });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },
};

module.exports = PageBlogControllers;
