import { Support } from "./supportModel.js";
import cloudinary from "../../Utils/cloudinary.js";

export const createSupport = async (req, res) => {
  // console.log(req.body);
  // console.log(req.files.image);
  try {
    // const { ticketId, createdOn, subject, description } = req.body;
    if(req.files && req.files.image){
    let images = [];
    let Allfiles = req.files.image;
    if (typeof Allfiles.tempFilePath === "string") {
      let filepath = Allfiles.tempFilePath;

      images.push(filepath);
    } else {
      Allfiles.map((item) => {
        images.push(item.tempFilePath);
      });
    }

    const imagesLinks = [];
    for (let i = 0; i < images.length; i++) {
      const result = await cloudinary.v2.uploader.upload(images[i], {
        folder: "smellica/CustomerSupport",
      });

      imagesLinks.push({
        public_id: result.public_id,
        url: result.secure_url,
      });
    }
    req.body.image = imagesLinks;
  }
    req.body.addedBy = req.user._id;
        // Check if any required field is missing
    // if (!ticketId || !createdOn || !subject || !description) {
    //   return res.status(400).json({
    //     success: false,
    //     msg: "All fields are required.",
    //   });
    // }

    // Create the support ticket
    // const support = await Support.create({
    //   ticketId,
    //   createdOn,
    //   subject,
    //   description,
    //   addedBy: req.user._id,
    //   image: imagesLinks,
    // });
    const support = await Support.create({ ...req.body });
    // Return the created support ticket
    res.status(201).json({
      success: true,
      data: support,
      msg: "Support ticket created successfully.",
    });
  } catch (error) {
    console.error(error);
    // Handle errors
    res.status(500).json({
      success: false,
      msg: error.message,
    });
  }
};
// ****************************

export const getAllSupportTicket = async (req, res) => {
  try {
    // Use the find method to retrieve all support tickets
    const support = await Support.find().sort({ createdAt: -1 });

    // Check if support tickets were found
    if (support) {
      return res.status(200).json({
        success: true,
        support,
      });
    }
  } catch (error) {
    // Handle errors
    // console.error(error);
    res.status(500).json({
      success: false,
      msg: error.message ? error.message : "Something went wrong!",
    });
  }
};
export const getOneSupportTicket = async (req, res) => {
  try {
    // console.log(req.params.id);
    const support = await Support.findOne({ ticketId: req.params.id });
    if (support) {
      return res.status(200).json({
        success: true,
        support,
      });
    } else {
      return res.status(404).json({
        success: false,
        msg: "Support ticket not found",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      msg: error.message ? error.message : "Something went wrong!",
    });
  }
};

// ************************8

export const getAllSupportTicketofuser = async (req, res) => {
  try {
    // Retrieve the user ID from the request
    const userId = req.user._id;

    // Use the find method to retrieve all support tickets created by the user
    const support = await Support.find({ addedBy: userId }).sort({
      createdAt: -1,
    });

    // Check if support tickets were found
    if (support) {
      return res.status(200).json({
        success: true,
        support,
      });
    } else {
      return res.status(404).json({
        success: false,
        msg: "No support tickets found for the user.",
      });
    }
  } catch (error) {
    // Handle errors
    // console.error(error);
    res.status(500).json({
      success: false,
      msg: error.message ? error.message : "Something went wrong!",
    });
  }
};

// ************************8

export const deleteSupport = async (req, res) => {
  try {
    if (!req.params.id) {
      return res.status(400).json({
        success: false,
        msg: "Please Provide Support ID!",
      });
    }
    // console.log(req.params.id);
    const getSupport = await Support.findById(req.params.id);
    if (!getSupport) {
      return res.status(404).json({
        success: false,
        msg: "Support not Found!",
      });
    }
    // Deleting Images From Cloudinary
    for (let i = 0; i < getSupport.image.length; i++) {
      await cloudinary.v2.uploader.destroy(getSupport.image[i].public_id);
    }

    //-------------------------//
    const supportticket = await Support.findByIdAndDelete(req.params.id);
    if (!supportticket) {
      return res.status(404).json({ message: "Support Not Found" });
    }
    await supportticket.remove();
    res.status(200).json({
      success: true,
      msg: "Support Deleted Successfully!!",
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      msg: error.message ? error.message : "Something went wrong!",
    });
  }
};

export const updateSupport = async (req, res) => {
  try {
    const { status, message } = req.body;
    // console.log(req.params.id);
    // Prepare an array for the images
    // const jsonArray = JSON.parse(image);
    // const AllImages = jsonArray.map(({ public_id, url }) => ({
    //   public_id,
    //   url,
    // }));

    // if (req.files && req.files.newImages) {
    //   const newuploadImages = Array.isArray(req.files.newImages)
    //     ? req.files.newImages
    //     : [req.files.newImages];

    //   const imagesLinks = [];

    //   for (let i = 0; i < newuploadImages.length; i++) {
    //     const result = await cloudinary.v2.uploader.upload(
    //       newuploadImages[i].tempFilePath,
    //       {
    //         folder: "smellica/product",
    //       }
    //     );

    //     imagesLinks.push({
    //       public_id: result.public_id,
    //       url: result.secure_url,
    //     });
    //   }

    // Combine the existing images and the newly uploaded images
    // const updatedImages = [...AllImages, ...imagesLinks];

    // Perform the product update
    // Find the support ticket by ID
    const supportTicket = await Support.findOne({ ticketId: req.params.id });
    // Check if the support ticket exists
    if (!supportTicket) {
      return res.status(404).json({
        success: false,
        msg: "Support ticket not found",
      });
    }

    // Update the support ticket fields
    if (status) {
      supportTicket.status = status;
    }
    if (message) {
      const newMessage = {
        message: message.message,
        user: message.user,
        replyDate: message.replyDate, // Add a timestamp to the message object
      };
      supportTicket.message.push(newMessage);
      // Update the last reply to the timestamp of the new message if the user is admin
      if (message.user === "admin") {
        supportTicket.lastreply = newMessage.replyDate;
      }
    }

    // Save the updated support ticket
    const updatedSupportTicket = await supportTicket.save();

    return res.status(200).json({
      success: true,
      updatedSupportTicket,
    });
  } catch (error) {
    // Handle errors
    // console.error(error);
    res.status(500).json({
      success: false,
      msg: error.message ? error.message : "Something went wrong!",
    });
  }
};
export const deleteImageFromCloudinary = async (req, res) => {
  const { public_id } = req.params;

  try {
    if (!public_id) {
      return res.status(400).json({
        success: false,
        msg: "Please Provide Product ID!",
      });
    }
    const response = await cloudinary.v2.uploader.destroy(public_id);
    if (response) {
      res.status(200).json({
        success: true,
        msg: "CustomerSupport Deleted Successfully!!",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      msg: error.message ? error.message : "Something went wrong!",
    });
  }
};