package controllers

import (
	"boss/internal/datas"
	"boss/internal/models/user"
	"boss/internal/utils/mfa"
	"github.com/beego/beego/v2/server/web"
)

type TotpQuery struct {
	web.Controller
}

func (c *TotpQuery) GenTotp() {
	userID, ok := c.GetSession("userID").(string)
	if !ok {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "提交信息错误",
		}
		_ = c.ServeJSON()
		return
	}
	newTotp, err := c.GetInt("newTotp")
	if err != nil {
		newTotp = 0
	}

	userInfo := user.GetUserInfoByUserID(userID)
	if userInfo.UserId == "" {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "当前用户不存在",
		}
		_ = c.ServeJSON()
		return
	}

	otpSecret := ""
	if userInfo.OtpSecret != "" && newTotp == 0 {
		otpSecret = userInfo.OtpSecret
	}
	otp, err := mfa.GetOtp(userInfo.UserId, userInfo.Nick, otpSecret, userInfo.OtpKey)
	if err != nil {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "当前用户不存在",
		}
		_ = c.ServeJSON()
		return
	}

	c.Data["json"] = datas.KeyDataJSON2{
		KeyDataJSON: datas.KeyDataJSON{
			Code: 0,
			Msg:  "成功",
			Key:  "",
		},
		Data: otp,
	}
	_ = c.ServeJSON()
}

func (c *TotpQuery) SaveTotp() {
	code := c.GetString("code")
	secret := c.GetString("secret")
	key := c.GetString("key")

	if code == "" || secret == "" || key == "" {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "提交消息不准确",
		}
		_ = c.ServeJSON()
		return
	}
	userID, ok := c.GetSession("userID").(string)
	if !ok {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "提交信息错误",
		}
		_ = c.ServeJSON()
		return
	}

	userInfo := user.GetUserInfoByUserID(userID)
	if userInfo.UserId == "" {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "当前用户不存在",
		}
		_ = c.ServeJSON()
		return

	}

	ok = mfa.ValidCode(code, secret)

	if !ok {
		c.Data["json"] = datas.KeyDataJSON{
			Code: -1,
			Msg:  "code验证错误",
		}
		_ = c.ServeJSON()
		return

	}

	err2 := user.UpdateOtpByUserID(userInfo.UserId, secret, key)
	if err2 != nil {
		c.Data["json"] = datas.BaseDataJSON{
			Code: -1,
			Msg:  "更新totp失败",
		}
		_ = c.ServeJSON()
		return

	}

	c.Data["json"] = datas.KeyDataJSON{
		Code: 0,
		Msg:  "success",
	}
	_ = c.ServeJSON()
}
