import ProductManual from "./ProductManualModel.js";
import cloudinary from "../../Utils/cloudinary.js";
import path from "path";
// Create a new product manual
export const createProductManual = async (req, res) => {
  const { title } = req.body;
  const pdfFile = req.files ? req.files.pdfFile : null;

  // Check if title is provided
  if (!title) {
    return res.status(400).json({
      success: false,
      message: "Title is required",
    });
  }

  // Check if a file is provided
  if (!pdfFile) {
    return res.status(400).json({
      success: false,
      message: "File is required",
    });
  }

  try {
    let productManualDetails = null;
    let filename = "";

    // Upload the file to Cloudinary
    if (pdfFile) {
      filename = pdfFile.name;
      // console.log(pdfFile);
      const originalFilename = path.basename(
        pdfFile.name,
        path.extname(pdfFile.name)
      );

      const result = await cloudinary.v2.uploader.upload(pdfFile.tempFilePath, {
        folder: "chemiNova/ProductManuals",
        public_id: originalFilename,
      });
      // console.log(result);
      productManualDetails = {
        public_id: result.public_id,
        url: result.secure_url,
        filename: filename,
      };
    }

    // Create the product manual
    const productManual = await ProductManual.create({
      title,
      product_manual: productManualDetails || {}, // Ensure product_manual is an empty object if no file is provided
    });

    res.status(201).json({
      success: true,
      productManual,
      message: "Product manual created successfully",
    });
  } catch (error) {
    console.error("Error creating product manual:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Internal server error",
    });
  }
};
// Get all product manuals
export const getAllProductManuals = async (req, res) => {
  try {
    const PAGE_SIZE = parseInt(req.query.show) || 10;
    const page = parseInt(req.query.page) || 1;
    const skip = (page - 1) * PAGE_SIZE;
    let filter = {};
    if (req.query.title) {
      filter.title = {
        $regex: new RegExp(req.query.title, "i"),
      };
    }

    // Fetch total count of documents
    const total = await ProductManual.countDocuments(filter);

    // Fetch paginated data
    const productManuals = await ProductManual.find(filter)
      .limit(PAGE_SIZE)
      .skip(skip)
      .sort({ createdAt: -1 })
      .exec();

    // Send response
    res.status(200).json({
      success: true,
      productManuals,
      total,
    });
  } catch (error) {
    console.error("Error fetching product manuals:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Internal server error",
    });
  }
};

// Get a single product manual by ID
export const getSingleProductManual = async (req, res) => {
  const { id } = req.params;

  try {
    const productManual = await ProductManual.findById(id);

    if (!productManual) {
      return res.status(404).json({
        success: false,
        message: "Product manual not found",
      });
    }

    res.status(200).json({
      success: true,
      productManual,
    });
  } catch (error) {
    console.error("Error fetching product manual:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Internal server error",
    });
  }
};

// Update a product manual
export const updateProductManual = async (req, res) => {
  const { id } = req.params;
  const { title } = req.body;
  try {
    const productManual = await ProductManual.findById(id);

    if (!productManual) {
      return res.status(404).json({
        success: false,
        message: "Product manual not found",
      });
    }
    let filename = "";
    // Check if a new file is provided
    if (req.files && req.files.pdfFile) {
      // Delete the old file from Cloudinary
      if (productManual.product_manual.public_id) {
        await cloudinary.v2.uploader.destroy(
          productManual.product_manual.public_id,
          {
            folder: "chemiNova/ProductManuals",
          }
        );
      }

      // Upload the new file to Cloudinary
      const pdfFile = req.files.pdfFile;
      // console.log(pdfFile);
      filename = pdfFile.name;
      const originalFilename = path.basename(
        pdfFile.name,
        path.extname(pdfFile.name)
      );

      const result = await cloudinary.v2.uploader.upload(pdfFile.tempFilePath, {
        folder: "chemiNova/ProductManuals",
        public_id: originalFilename,
      });
      // console.log(result);
      // Update the product manual details
      productManual.product_manual = {
        public_id: result.public_id,
        url: result.secure_url,
        filename: filename,
      };
    }

    // Update the title
    productManual.title = title || productManual.title;
    // console.log(productManual);
    await productManual.save();

    res.status(200).json({
      success: true,
      productManual,
      message: "Product manual updated successfully",
    });
  } catch (error) {
    console.error("Error updating product manual:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Internal server error",
    });
  }
};

// Delete a product manual
export const deleteProductManual = async (req, res) => {
  const { id } = req.params;

  try {
    const productManual = await ProductManual.findById(id);

    if (!productManual) {
      return res.status(404).json({
        success: false,
        message: "Product manual not found",
      });
    }

    // Delete the file from Cloudinary
    if (productManual.product_manual.public_id) {
      await cloudinary.v2.uploader.destroy(
        productManual.product_manual.public_id,
        {
          folder: "chemiNova/ProductManuals",
        }
      );
    }

    // Delete the product manual from the database
    await ProductManual.findByIdAndDelete(id);

    res.status(200).json({
      success: true,
      message: "Product manual deleted successfully",
    });
  } catch (error) {
    console.error("Error deleting product manual:", error);
    res.status(500).json({
      success: false,
      message: error.message || "Internal server error",
    });
  }
};
