package users

import (
	"context"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	v1 "hotgo/api/api/users/v1"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/model/entity"
	utility "hotgo/utility/jwt"
)

func (c *ControllerV1) Login(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
	// 1. 查找用户
	user := &entity.Users{}
	err = dao.Users.Ctx(ctx).Where("phone = ?", req.Phone).Scan(user)
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "数据库错误")
	}
	if user.Id == 0 {
		return nil, gerror.NewCode(consts.CodeUserNotFound, "用户不存在")
	}

	// 2. 校验密码（sha256+salt）
	hashedPwd := utility.HashPassword(req.Password, user.Salt)
	if user.Password != hashedPwd {
		return nil, gerror.NewCode(consts.CodePasswordInvalid, "密码错误")
	}

	// 3. 生成JWT Token
	token, err := utility.GenerateToken(user.Id)
	if err != nil {
		return nil, gerror.NewCode(consts.CodeInternalError, "生成Token失败")
	}

	res = &v1.LoginRes{
		Token: token,
	}
	return
}
