package lending

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// GetTokensInfo returns information about all supported tokens
// GET /api/lending/tokens?chain_id=97
func GetTokensInfo(c *gin.Context) {
	chainId := parseChainID(c)

	stablecoins, err := GetAllStablecoins(chainId)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"error":   "failed to fetch stablecoins",
		})
		return
	}

	ytTokens, err := GetAllYTTokens(chainId)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"error":   "failed to fetch YT tokens",
		})
		return
	}

	allTokens := make([]TokenInfo, 0, len(stablecoins)+len(ytTokens))
	allTokens = append(allTokens, stablecoins...)
	allTokens = append(allTokens, ytTokens...)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data": gin.H{
			"stablecoins": stablecoins,
			"yt_tokens":   ytTokens,
			"all_tokens":  allTokens,
		},
	})
}

// GetTokenInfo returns information about a specific token
// GET /api/lending/tokens/:assetCode?chain_id=97
func GetTokenInfo(c *gin.Context) {
	assetCode := c.Param("assetCode")
	chainId := parseChainID(c)

	info, err := GetTokenInfoFromDB(assetCode)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"success": false,
			"error":   "token not found",
		})
		return
	}
	info.Decimals = resolveDecimals(info.ContractAddress, chainId, info.Decimals)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    info,
	})
}

// parseChainID reads chain_id from query string, returns 0 if not provided
func parseChainID(c *gin.Context) int {
	s := c.Query("chain_id")
	if s == "" {
		return 0
	}
	id, err := strconv.Atoi(s)
	if err != nil {
		return 0
	}
	return id
}
