// routes/token.js
const express = require("express");
const router = express.Router();
const Token = require("../models/token.model.js");
const TradingToken = require("../models/leaderboard.model.js");

// GET /api/tokens/latest-prices
router.get("/latest-prices", async (req, res) => {
  try {
    const tokens = await Token.find();

    const results = await Promise.all(
      tokens.map(async (token) => {
        const latestTrading = await TradingToken.findOne({
          tokenAddress: token.tokenAddress,
        })
          .sort({ createdAt: -1 })
          .exec();

        if (!latestTrading || !latestTrading.tokenprice) {
          return null; // Ignore tokens without price
        }

        return {
          symbol: token.symbol,
          latestPrice: latestTrading.tokenprice,
        };
      })
    );

    // Filter out null entries
    const filteredResults = results.filter((item) => item !== null);

    res.json(filteredResults);
  } catch (err) {
    console.error("Error fetching token prices:", err);
    res.status(500).json({ message: "Server error" });
  }
});

module.exports = router;
