// Filename: internal/handlers/tokens_handler.go

package handlers

import (
	"gemini-balancer/internal/errors"
	"gemini-balancer/internal/models"
	"gemini-balancer/internal/response"
	"gemini-balancer/internal/service"

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

type TokensHandler struct {
	db           *gorm.DB
	tokenManager *service.TokenManager
}

func NewTokensHandler(db *gorm.DB, tm *service.TokenManager) *TokensHandler {
	return &TokensHandler{
		db:           db,
		tokenManager: tm,
	}
}

func (h *TokensHandler) GetAllTokens(c *gin.Context) {
	tokensFromCache := h.tokenManager.GetAllTokens()
	//TODO 可以像KeyGroupResponse一样，创建一个TokenResponse DTO来整理数据
	response.Success(c, tokensFromCache)
}

func (h *TokensHandler) UpdateTokens(c *gin.Context) {
	var incomingTokens []*models.TokenUpdateRequest
	if err := c.ShouldBindJSON(&incomingTokens); err != nil {
		response.Error(c, errors.NewAPIError(errors.ErrInvalidJSON, err.Error()))
		return
	}

	if err := h.tokenManager.BatchUpdateTokens(incomingTokens); err != nil {
		response.Error(c, errors.NewAPIError(errors.ErrInternalServer, "Failed to update tokens: "+err.Error()))
		return
	}
	response.Success(c, gin.H{"message": "Tokens updated successfully."})
}

// [TODO]
// func (h *TokensHandler) CreateToken(c *gin.Context) {
//     ... 数据库写操作 ...
//     h.tokenManager.Invalidate() // 写后，立即让缓存失效
// }
