/**
 * BlogPost controllers
 * Mirrors style of CategoryControllers
 */

const { blogPost } = require("../../models/blogs/blogPostModel");
const path = require("path");
const fs = require("fs");
const { Op } = require("sequelize");

const uploadDir = "uploads/blog_images";

const BlogPostControllers = {
createPost: async (req, res) => {
  try {
    const created_by = req.user.id;
    const {
      title,
      slug,
      image_alt,
      content,
      section,
      category_id,
      is_featured,
      is_active
    } = req.body;

    const data = {
      title: title?.trim(),
      slug: slug?.trim(),
      image_alt: image_alt?.trim() || null,
      content: content || "",
      section: parseInt(section) || 1,
      category_id: parseInt(category_id),
      is_featured: is_featured === "1" || is_featured === "true",
      is_active: is_active === "1" || is_active === "true",
      created_by: created_by,
    };

    if (req.file) {
      data.feature_image = `/uploads/blog_images/${req.file.filename}`;
    }

    const result = await blogPost.create(data);

    if (result?.error) {
      return res.status(400).json({ success: false, message: result.error });
    }

    if (req.file) {
      data.feature_image = `/uploads/blog_images/${req.file.filename}`;
    }
    res.status(201).json({
      success: true,
      message: "Blog post created successfully!",
      data: result,
    });

  } catch (err) {
    console.error("Error in createPost:", err);
    res.status(500).json({ success: false, message: err.message });
  }
},

  /* ---------- READ ALL ---------- */
  getAllPosts: async (req, res) => {
  try {
    const filters = {};

    if (req.query.is_active !== undefined) {
      filters.is_active =
        req.query.is_active === "true" || req.query.is_active === "1";
    }

    if (req.query.is_featured !== undefined) {
      filters.is_featured =
        req.query.is_featured === "true" || req.query.is_featured === "1";
    }

    const posts = await blogPost.getAll(filters); 

    if (!posts.length) {
      return res
        .status(404)
        .json({ success: false, message: "No posts found" });
    }

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

  /* ---------- READ SINGLE ---------- */
  getSinglePost: async (req, res) => {
    try {
      const post = await blogPost.getSingle(req.params.id);
      if (!post) {
        return res.status(404).json({ success: false, message: "Post not found" });
      }
      res.status(200).json({ success: true, data: post });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  /* ---------- UPDATE ---------- */
 
updatePost: async (req, res) => {
  try {
    const {
      title,
      slug,
      image_alt,
      content,
      section,
      category_id,
      is_featured,
      is_active,
    } = req.body;

    const data = {
      title: title?.trim(),
      slug: slug?.trim(),
      image_alt: image_alt?.trim() || null,
      content,
      section: section ? parseInt(section) : undefined,
      category_id: category_id ? parseInt(category_id) : undefined,
      is_featured:
        typeof is_featured !== "undefined"
          ? is_featured === "1" || is_featured === "true"
          : undefined,
      is_active:
        typeof is_active !== "undefined"
          ? is_active === "1" || is_active === "true"
          : undefined,
    };

    // remove undefined keys so we don’t overwrite with null
    Object.keys(data).forEach((k) => data[k] === undefined && delete data[k]);

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

    const updated = await blogPost.update(req.params.id, data);

    if (updated?.error) {
      return res.status(400).json({ success: false, message: updated.error });
    }
    if (!updated) {
      return res
        .status(404)
        .json({ success: false, message: "Post not found" });
    }

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

  /* ---------- DELETE ---------- */
  deletePost: async (req, res) => {
    try {
      const deleted = await blogPost.delete(req.params.id);
      if (!deleted) {
        return res.status(404).json({ success: false, message: "Post not found" });
      }
      res.status(200).json({ success: true, ...deleted });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },


  //get single blog usign slug
    getSinglePostBySlug: async (req, res) => {
  try {
    const post = await blogPost.getSinglebyslug(req.params.slug);
    if (!post) {
      return res.status(404).json({ success: false, message: "Post not found" });
    }
    res.status(200).json({ success: true, data: post });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
},

};

module.exports = BlogPostControllers;
