const TradingToken = require("../models/leaderboard.model.js");
// const multer = require("multer");
// const path = require("path");
// const fs = require("fs");
// const imageDir = path.join(__dirname, "../images/");

// Image Path
// if (!fs.existsSync(imageDir)) {
//   fs.mkdirSync(imageDir, { recursive: true });
// }
// const storage = multer.diskStorage({
//   destination: (req, file, cb) => {
//     cb(null, imageDir);
//   },
//   filename: (req, file, cb) => {
//     const uniqueName = `${Date.now()}-${file.originalname}`;
//     cb(null, uniqueName);
//   },
// });

// const upload = multer({
//   storage: storage,
// });

// Post Token
const postTrading = async (req, res) => {
  try {
    // const uploadMiddleware = upload.fields([{ name: "image", maxCount: 1 }]);
    // await new Promise((resolve, reject) =>
    //   uploadMiddleware(req, res, (err) => {
    //     if (err) reject(err);
    //     else resolve();
    //   })
    // );

    // const { body, files } = req;
    // const file = files?.image?.[0];
    // if (!file) {
    //   return res.status(400).json({ message: "Image file is required" });
    // }

    // const tokenAddress = uuidv4();

    // const TokenData = {
    //   ...body,
    //   image: `../images/${file.filename}`,
    // };
 const userId = req.user.userId;
 const tradingData = {
   userId,
   ...req.body,
 };
    const trading = await TradingToken.create(tradingData);

    res.status(200).json({
      message: "Trading Token data successfully created",
      trading,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// Get Token Details

const getTrading = async (req, res) => {
  try {
    const trading = await TradingToken.find({});
    // const fullUrl = `${req.protocol}://${req.get("host")}`;

    // // Append full image URLs
    // const tokenData = tokens.map((token) => ({
    //   ...token._doc, // Spread the existing token fields
    //   image: token.image ? `${fullUrl}/images/${token.image}` : null,
    // }));

    res.status(200).json(trading);
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({ message: err.message });
  }
};

// Get Token Details By Id

const getTradingByID = async (req, res) => {
  try {
    const { id } = req.params;
    const tradingData = await TradingToken.findById(id);
    res.status(200).json(tradingData);
  } catch (err) {
    console.log("Error", err);
    res.status(500).json({ message: err.message });
  }
};

const getUserTrade = async (req, res) => {
  try {
    const userId = req.user.userId;
    const tradingData = await TradingToken.find({ userId });
    res.status(200).json(tokens);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// Get Token Details By Id

const getTradingByAddress = async (req, res) => {
  try {
    const { tokenAddress } = req.params;
    const trading = await tradingData.findOne({ tokenAddress });

    if (!trading) {
      return res.status(404).json({ message: "Token not found" });
    }
    // const imageUrl = `${req.protocol}://${req.get("host")}/images/${
    //   tokenData.image
    // }`;
    // const response = {
    //   ...tokenData.toObject(),
    //   image: imageUrl,
    // };

    res.status(200).json(trading);
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({ message: err.message });
  }
};

// Get Token Details By Id

// const updateToken = async (req, res) => {
//   try {
//     const uploadMiddleware = upload.fields([{ name: "image", maxCount: 1 }]);
//     await new Promise((resolve, reject) =>
//       uploadMiddleware(req, res, (err) => {
//         if (err) reject(err);
//         else resolve();
//       })
//     );

//     const { id } = req.params;
//     const { body, files } = req;

//     const existingToken = await Token.findById(id);
//     if (!existingToken) {
//       return res.status(404).json({ message: "Token not found" });
//     }

//     const file = files?.image?.[0];
//     if (file) {
//       if (existingToken.image && fs.existsSync(existingToken.image)) {
//         fs.unlinkSync(existingToken.image);
//       }
//       body.image = `../images/${file.filename}`;
//     }

//     const updatedToken = await Token.findByIdAndUpdate(id, body, {
//       new: true,
//       runValidators: true,
//     });

//     res.status(200).json({
//       success: true,
//       message: "Token successfully updated",
//       data: updatedToken,
//     });
//   } catch (error) {
//     res.status(500).json({ message: error.message });
//   }
// };

const deleteTrading = async (req, res) => {
  try {
    const { id } = req.params;
    const trading = await TradingToken.findByIdAndDelete(id);
    if (!trading) {
      res.status(400).json({ message: "Token Not Find" });
    }
    res.status(200).json({ message: "Token has been deleted Successfully" });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

module.exports = {
  postTrading,
  getTradingByAddress,
  getTradingByID,
  getTrading,
  deleteTrading,
  getUserTrade,
};
