// Filename: internal/handlers/api_auth_handler.go
package handlers

import (
	"gemini-balancer/internal/middleware"
	"gemini-balancer/internal/service"
	"net/http"

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

type APIAuthHandler struct {
	securityService *service.SecurityService
}

func NewAPIAuthHandler(securityService *service.SecurityService) *APIAuthHandler {
	return &APIAuthHandler{securityService: securityService}
}

type LoginRequest struct {
	Token string `json:"token" binding:"required"`
}

type LoginResponse struct {
	Token   string `json:"token"`
	Message string `json:"message"`
}

func (h *APIAuthHandler) HandleLogin(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误: " + err.Error()})
		return
	}

	authToken, err := h.securityService.AuthenticateToken(req.Token)
	// 同时检查token是否有效，以及是否是管理员
	if err != nil || !authToken.IsAdmin {
		h.securityService.RecordFailedLoginAttempt(c.Request.Context(), c.ClientIP())
		c.JSON(http.StatusUnauthorized, gin.H{"error": "无效或非管理员Token"})
		return
	}

	middleware.SetAdminSessionCookie(c, authToken.Token)

	c.JSON(http.StatusOK, LoginResponse{
		Token:   authToken.Token,
		Message: "登录成功，欢迎管理员！",
	})
}
