const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

async function createCategory(req, res) {
  const { name, blogIDs, blogs } = req.body;
  try {
    const newCategory = await prisma.Category.create({
      data: {
        name,
        blogIDs,
        blogs,
      },
    });
    res.status(201).json(newCategory);
  } catch (error) {
    console.error("Error creating comment:", error);
    res.status(500).json({ message: "Error creating blog" });
  }
}

async function getCategory(req, res) {
  try {
    const categories = await prisma.Category.findMany();
    res.json(categories);
  } catch (error) {
    console.error("Error getting blogs:", error);
    res
      .status(500)
      .json({ message: "Error getting blogs", error: error.message });
  }
}

async function updateCategory(req, res) {
  const { name, blog, blogIDs } = req.body;
  const id = req.params.id;
  try {
    const Categories = await prisma.Category.findUnique({
      where: { id },
    });
    if (!Categories) {
      return res.status(404).send({
        message: "Comment not found",
      });
    }
    const updatedCategory = await prisma.Category.update({
      where: { id },
      data: {
        name,
        blog,
        blogIDs,
      },
    });

    res.status(200).send(updatedCategory);
  } catch (error) {
    console.error("Error updating Category:", error);
    res.status(500).send({
      message: "Error updating Category",
      error: error.message,
    });
  }
}

async function deleteCategory(req, res) {
  const { id } = req.params;
  try {
    const delCategory = await prisma.Category.delete({
      where: { id },
    });
    res.json(delCategory);
  } catch (error) {
    console.error("Error deleting comment:", error);
    res
      .status(500)
      .json({ message: "Error deleting comment", error: error.message });
  }
}

module.exports = {
  createCategory,
  getCategory,
  updateCategory,
  deleteCategory,
};
