const db = require("../../db");

exports.createBlogCategory = async (req, res) => {
  try {
    const { categoryName } = req.body;

    if (!categoryName) {
      return res.status(400).json({
        success: false,
        error: "Category name is required",
      });
    }

    // Check if category exists (only checking title)
    const existingCategory = await db.BlogCategory.findOne({
      where: { ppc_title: categoryName },
    });

    if (existingCategory) {
      return res.status(400).json({
        success: false,
        error: "Category already exists",
      });
    }

    // Create with only the title field
    const newCategory = await db.BlogCategory.create({
      ppc_title: categoryName,
    });

    res.status(201).json({
      success: true,
      message: "Category created successfully",
      data: {
        ppc_id: newCategory.ppc_id,
        categoryName: newCategory.ppc_title,
      },
    });
  } catch (err) {
    console.error("Error creating category:", err);
    res.status(500).json({
      success: false,
      error: "Failed to create category",
    });
  }
};

exports.getBlogCategories = async (req, res) => {
  try {
    const categories = await db.BlogCategory.findAll({
      attributes: ["ppc_id", "ppc_title"],
      order: [["ppc_created_date", "DESC"]],
    });

    res.json({
      success: true,
      data: categories.map((cat) => ({
        ppc_id: cat.ppc_id,
        categoryName: cat.ppc_title,
      })),
    });
  } catch (err) {
    console.error("Error fetching categories:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch categories",
    });
  }
};

exports.deleteBlogCategory = async (req, res) => {
  try {
    const { id } = req.params;

    const category = await db.BlogCategory.findByPk(id);
    if (!category) {
      return res.status(404).json({
        success: false,
        error: "Category not found",
      });
    }

    await category.destroy();

    res.json({
      success: true,
      message: "Category deleted successfully",
    });
  } catch (err) {
    console.error("Error deleting category:", err);
    res.status(500).json({
      success: false,
      error: "Failed to delete category",
    });
  }
};
