package admin

import (
    "net/http"
    "time"

    "bindbox-game/configs"
    "bindbox-game/internal/code"
    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/jwtoken"
    "bindbox-game/internal/pkg/utils"
)

type refreshResponse struct {
    Token     string `json:"token"`
    ExpiresIn int64  `json:"expires_in"`
}

// RefreshToken 刷新管理员访问令牌
// @Summary 管理端令牌刷新
// @Tags 管理端.登录
// @Accept json
// @Produce json
// @Success 200 {object} refreshResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/auth/refresh [post]
// @Security LoginVerifyToken
func (h *handler) RefreshToken() core.HandlerFunc {
    return func(ctx core.Context) {
        auth := ctx.Request().Header.Get("Authorization")
        if auth == "" {
            ctx.AbortWithError(core.Error(http.StatusUnauthorized, code.AdminLoginError, "未携带令牌"))
            return
        }
        newToken, err := jwtoken.New(configs.Get().JWT.AdminSecret).Refresh(auth)
        if err != nil || newToken == "" {
            ctx.AbortWithError(core.Error(http.StatusUnauthorized, code.AdminLoginError, "令牌刷新失败"))
            return
        }
        info := ctx.SessionUserInfo()
        if info.Id > 0 {
            _, _ = h.writeDB.Admin.WithContext(ctx.RequestContext()).Where(h.writeDB.Admin.ID.Eq(int32(info.Id))).Updates(map[string]any{
                "last_login_time": time.Now(),
                "last_login_ip":  utils.GetIP(ctx.Request()),
                "last_login_hash": utils.MD5(newToken),
            })
        }
        ctx.Payload(refreshResponse{Token: newToken, ExpiresIn: int64(24 * 3600)})
    }
}