package controller

import (
	"net/http"

	"metazone.cc/metalab/internal/common"

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

// LevelController 积分/等级/签到 API
type LevelController struct {
	levelSvc levelUseCase
}

// NewLevelController 构造函数
func NewLevelController(levelSvc levelUseCase) *LevelController {
	return &LevelController{levelSvc: levelSvc}
}

// CheckIn 手动签到 API（已废弃前端手动按钮，保留后端接口）
func (lc *LevelController) CheckIn(c *gin.Context) {
	uidVal, exists := c.Get("uid")
	if !exists {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}
	uid := uidVal.(uint)

	checkedIn, newExp, levelUp, err := lc.levelSvc.CheckIn(uid)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "签到失败")
		return
	}

	level, _, _, _ := lc.levelSvc.GetLevel(uid)
	common.Ok(c, gin.H{
		"checked_in": checkedIn,
		"exp":        newExp,
		"level":      level,
		"level_up":   levelUp,
	})
}

// GetLevel 获取当前等级、经验值和签到状态 API
func (lc *LevelController) GetLevel(c *gin.Context) {
	uidVal, exists := c.Get("uid")
	if !exists {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}
	uid := uidVal.(uint)

	level, exp, checkedIn, err := lc.levelSvc.GetLevel(uid)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "获取失败")
		return
	}

	common.Ok(c, gin.H{"level": level, "exp": exp, "checked_in": checkedIn})
}
