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

exports.createBlogTag = async (req, res) => {
  try {
    const requiredFields = ["tagname"];
    const missingFields = requiredFields.filter((field) => !req.body[field]);

    if (missingFields.length > 0) {
      return res.status(400).json({
        error: "Missing required fields",
        missingFields,
      });
    }
    const existingTags = await db.BlogTag.findOne({
      where: { tag_name: req.body.tagname },
    });

    if (existingTags) {
      return res.status(400).json({ error: "College already exists" });
    }

    const dbData = {
      tag_name: req.body.tagname,
    };

    const tag = await db.BlogTag.create(dbData);

    res.status(201).json({
      success: true,
      message: "Blog Tag created successfully",
      tagname: db.BlogTag.tag_name,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to create Blog tag",
      details:
        process.env.NODE_ENV === "development"
          ? { message: err.message, stack: err.stack }
          : undefined,
    });
  }
};

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

    if (id) {
      const blogTag = await db.BlogTags.findByPk(id);

      if (!blogTag) {
        return res.status(404).json({ error: "College not found" });
      }
      return res.json(blogTag);
    }

    const blogTags = await db.BlogTag.findAll();
    return res.json(blogTags);
  } catch (err) {
    console.error("Error fetching blog tag:", err);
    res.status(500).json({ error: "Failed to fetch blog tag" });
  }
};
