package user

import (
	"Crimson-Gatekeeper/internal/common"
	"Crimson-Gatekeeper/internal/ero"
	"Crimson-Gatekeeper/internal/query"
	"context"
	"fmt"

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

const version = "/api/v1"
const group = "/user"

type Controller struct {
	query *query.Query
}

type postLoginParam struct {
	Account  string `json:"account" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func (c *Controller) postLogin(ctx *gin.Context) {
	param := &postLoginParam{}
	if err := ctx.ShouldBindJSON(&param); err != nil {
		fmt.Println("参数解析失败，请确认参数是否为 JSON")
		fmt.Println(err)
	}
	u := c.query.User
	user, err := u.WithContext(context.Background()).Where(u.Account.Eq(param.Account)).Take()
	if err != nil {
		fmt.Println("查询错误")
		common.SetData(ctx, ero.SimpleError("服务器繁忙，请稍后重试"))
	}
	if user == nil {
		fmt.Println("没有找到用户")
		return
	}
	if user.Passwd != param.Password {
		fmt.Println("用户密码错误")
		return
	}
}

func (c *Controller) RegisterRoute(gin *gin.Engine) {
	group := gin.Group(version).Group(group)
	group.POST("/login", c.postLogin)
}

// New 获取用户模块的控制器
//
// 参数
//   - gorm.DB 该模块所使用的数据库链接
//
// 返回值
//   - Controller 控制器的实例指针
func New(param *query.Query) *Controller {
	return &Controller{param}
}
