// Package controller 控制器层
package controller

import (
	"server/common"
	"server/modules/system/service"

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

// LoginRequest 登录请求
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// AuthController 认证控制器
type AuthController struct {
	userService *service.SysUserService
}

func NewAuthController() *AuthController {
	return &AuthController{userService: service.NewSysUserService()}
}

func (ctrl *AuthController) RegisterRoutes(r *gin.RouterGroup) {
	r.POST("/user/auth/login", ctrl.Login)
	r.POST("/user/auth/logout", ctrl.Logout)
	r.GET("/user/auth/info", ctrl.GetUserInfo)
}

// Login 用户登录
// @Summary      用户登录
// @Tags         认证
// @Accept       json
// @Produce      json
// @Param        request  body  LoginRequest  true  "登录信息"
// @Success      200  {object}  common.Response
// @Router       /user/auth/login [post]
func (ctrl *AuthController) Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, 400, "用户名和密码不能为空")
		return
	}

	loginUser, token, err := ctrl.userService.Login(req.Username, req.Password)
	if err != nil {
		common.Error(c, 400, err.Error())
		return
	}

	common.Success(c, gin.H{
		"token": token,
		"user":  loginUser,
	})
}

// Logout 用户登出
// @Summary      用户登出
// @Tags         认证
// @Success      200  {object}  common.Response
// @Router       /user/auth/logout [post]
func (ctrl *AuthController) Logout(c *gin.Context) {
	token := c.GetHeader("Authorization")
	if len(token) > 7 {
		token = token[7:] // 去除 "Bearer "
	}

	ctrl.userService.Logout(token)
	common.Success(c, nil)
}

// GetUserInfo 获取当前登录用户信息
// @Summary      获取当前登录用户信息
// @Tags         认证
// @Success      200  {object}  common.Response
// @Router       /user/auth/info [get]
func (ctrl *AuthController) GetUserInfo(c *gin.Context) {
	user := common.GetLoginUser(c)
	if user == nil {
		common.Error(c, 401, "未登录")
		return
	}
	common.Success(c, user)
}
