const { PrismaClient } = require("@prisma/client");
const fs = require("fs");
const csv = require("csv-parser");
const prisma = new PrismaClient();
const blogSchema = require("../validations");

// Create a blog
exports.createBlog = async (req, res) => {
  try {
    const { slug, title, body, categoryIDs, tagIDs } = req.body;
    const coverImage = req.file ? req.file.path : null;

    const newBlog = await prisma.blog.create({
      data: {
        slug,
        title,
        body,
        coverImage,
        // Ensure categoryIDs and tagIDs are correctly processed
        categoryIDs: categoryIDs ? categoryIDs.split(",") : [],
        tagIDs: tagIDs ? tagIDs.split(",") : [],
      },
    });
    res.status(201).json(newBlog);
  } catch (error) {
    console.error("Error creating blog:", error);
    res.status(500).json({ error: error.message });
  }
};

exports.bulkUploadBlogs = async (req, res) => {
  try {
    const results = [];
    await new Promise((resolve, reject) => {
      fs.createReadStream(req.file.path)
        .pipe(csv())
        .on("data", (data) => results.push(data))
        .on("end", resolve)
        .on("error", reject);
    });

    const blogs = await prisma.blog.createMany({
      data: results.map((blog) => ({
        slug: blog.slug,
        title: blog.title,
        body: blog.body,
        categoryIDs: blog.categoryIDs ? JSON.parse(blog.categoryIDs) : [],
        tagIDs: blog.tagIDs ? JSON.parse(blog.tagIDs) : [],
      })),
    });

    res.status(201).json({ count: blogs.count });
  } catch (error) {
    console.error("Error in bulk upload:", error);
    res.status(500).json({ error: error.message });
  }
};

// Get all blogs
exports.getBlogs = async (req, res) => {
  try {
    const blogs = await prisma.blog.findMany({
      include: { categories: true, tags: true, comments: true },
    });
    res.status(200).json(blogs);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Update a blog
exports.updateBlog = async (req, res) => {
  try {
    const { id } = req.params;
    const { slug, title, body, categoryIDs, tagIDs } = req.body;

    // Update the blog
    const updatedBlog = await prisma.blog.update({
      where: { id },
      data: {
        slug,
        title,
        body,
        categoryIDs: categoryIDs.map((id) => new prisma.ObjectId(id)), // Ensure IDs are converted
        tagIDs: tagIDs.map((id) => new prisma.ObjectId(id)), // Ensure IDs are converted
      },
    });

    res.status(200).json(updatedBlog);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Delete a blog
exports.deleteBlog = async (req, res) => {
  try {
    const { id } = req.params;
    await prisma.blog.delete({ where: { id } });
    res.status(204).send();
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

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

// // Create a blog with a cover image
// exports.createBlog = async (req, res) => {
//   try {
//     const { slug, title, body, categoryIDs, tagIDs } = req.body;
//     const coverImage = req.file ? req.file.path : null;

//     // Create the blog post
//     const newBlog = await prisma.blog.create({
//       data: {
//         slug,
//         title,
//         body,
//         coverImage,
//         categoryIDs,
//         tagIDs,
//       },
//     });
//     res.status(201).json(newBlog);
//   } catch (error) {
//     console.error("Error creating blog:", error);
//     res.status(500).json({ error: "Internal server error" });
//   }
// };
