const Token = require("../models/token.model.js");

// POST: Create Token (no image upload)
const postToken = async (req, res) => {
  try {
    const userId = req.user.userId;
    const tokenData = {
      userId,
      ...req.body,
    };

    const token = await Token.create(tokenData);

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

// GET: All tokens
const getToken = async (req, res) => {
  try {
    const tokens = await Token.find({});
    res.status(200).json(tokens);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// GET: Tokens by user
const getUserTokens = async (req, res) => {
  try {
    const userId = req.user.userId;
    const tokens = await Token.find({ userId });
    res.status(200).json(tokens);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// GET: Token by ID
const getTokenByID = async (req, res) => {
  try {
    const { id } = req.params;
    const tokenData = await Token.findById(id);
    res.status(200).json(tokenData);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// GET: Token by address
const getTokenByAddress = async (req, res) => {
  try {
    const { tokenAddress } = req.params;
    const tokenData = await Token.findOne({ tokenAddress });

    if (!tokenData) {
      return res.status(404).json({ message: "Token not found" });
    }

    res.status(200).json(tokenData);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// PUT: Update Token (no image update)
const updateToken = async (req, res) => {
  try {
    const { id } = req.params;
    const updatedToken = await Token.findByIdAndUpdate(id, req.body, {
      new: true,
      runValidators: true,
    });

    if (!updatedToken) {
      return res.status(404).json({ message: "Token not found" });
    }

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

// DELETE: Token
const deleteToken = async (req, res) => {
  try {
    const { id } = req.params;
    const token = await Token.findByIdAndDelete(id);

    if (!token) {
      return res.status(404).json({ message: "Token not found" });
    }

    res.status(200).json({ message: "Token deleted successfully" });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

const checkUserHasToken = async (req, res) => {
  try {
    const userId = req.user.userId;

    const userToken = await Token.findOne({ userId });

    if (userToken) {
      return res.status(200).json({
        status: "success",
        hasToken: true,
        token: userToken.token,
      });
    } else {
      return res.status(200).json({
        status: "success",
        hasToken: false,
        message: "User has not created any token.",
      });
    }
  } catch (err) {
    console.error("Error checking user token:", err);
    return res.status(500).json({
      status: "error",
      message: "Server error while checking token.",
    });
  }
};

const getUnusedTokensForUser = async (req, res) => {
  try {
    const userId = req.user.userId;

    const tokens = await Token.find({
      userId,
      status: "unused",
    });

    res.json({
      status: "success",
      tokens,
    });
  } catch (err) {
    console.error("Error fetching tokens:", err);
    res.status(500).json({
      status: "error",
      message: "Failed to fetch unused tokens",
      details: err.message,
    });
  }
};

module.exports = {
  postToken,
  getToken,
  getTokenByID,
  updateToken,
  getTokenByAddress,
  deleteToken,
  getUserTokens,
  checkUserHasToken,
  getUnusedTokensForUser,
};
