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

async function createBlog(req, res) {
  const { slug, title, body, categoryIDs, tagIDs } = req.body;
  const coverImage = req.file ? req.file.path : null;
  try {
    const newBlog = await prisma.Blog.create({
      data: {
        slug,
        title,
        body,
        coverImage,
        categoryIDs,
        tagIDs,
      },
    });
    res.status(201).json(newBlog);
  } catch (error) {
    console.error("Error creating comment:", error);
    res.status(500).json({ message: "Error creating blog" });
  }
}

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

async function updateBlog(req, res) {
  const { slug, title, body, categoryIDs, tagIDs } = req.body;
  const id = req.params.id;

  try {
    const blog = await prisma.Blog.findUnique({
      where: { id },
    });

    if (!blog) {
      return res.status(404).send({
        message: "Blog not found",
      });
    }

    const updatedBlog = await prisma.Blog.update({
      where: { id },
      data: {
        slug,
        title,
        body,
        categoryIDs,
        tagIDs,
      },
    });

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

async function deleteBlog(req, res) {
  const { id } = req.params;

  try {
    const blog = await prisma.Blog.delete({
      where: { id },
    });
    res.json(blog);
  } catch (error) {
    console.error("Error deleting blog:", error);
    res
      .status(500)
      .json({ message: "Error deleting blog", error: error.message });
  }
}

module.exports = {
  createBlog,
  getBlogs,
  updateBlog,
  deleteBlog,
};
