package mw

import (
	"errors"

	"applet/app/db"
	"applet/app/e"
	"applet/app/lib/arkid"
	"applet/app/md"
	"applet/app/utils"

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

// 检查权限, 签名等等
func Auth(c *gin.Context) {

	for k, v := range c.Request.Header {
		c.Set(k, v[0])
	}
	token, ok := c.Get("Token")
	if !ok {
		e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("没有找到token"))
		return
	}
	if token == "" {
		e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空"))
		return
	}
	tokenStr := utils.AnyToString(token)
	arkIdSdk := arkid.NewArkID()
	var err error
	signUser := &md.User{}
	arkIdUser := new(arkid.ArkIDUser)
	if err = arkIdSdk.SelectFunction("arkid_user_info").
		WithArgs(arkid.RequestBody{Token: tokenStr}).
		Result(arkIdUser); err != nil {
		e.OutErr(c, e.ERR_TOKEN_AUTH, err) //token 不存在
		return
	}
	if arkIdUser.Username == "" {
		e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("Token error"))
		return
	}
	if err = arkIdSdk.SelectFunction("arkid_login").
		WithArgs(arkid.RequestBody{Username: arkIdUser.Username, Password: utils.Md5(arkIdUser.Username)}).
		Result(arkIdUser); err != nil {
		e.OutErr(c, e.ERR_TOKEN_AUTH, err)
		return
	}
	signUser.Ark = arkIdUser
	if signUser.Ark == nil {
		e.OutErr(c, e.ERR_TOKEN_AUTH, errors.New("无效token"))
		return
	}
	signUser.Info, err = db.UserFindByArkidUserName(db.DBs[c.GetString("mid")], arkIdUser.Username)
	if err != nil {
		e.OutErr(c, e.ERR_TOKEN_AUTH, err)
		return
	}
	if signUser.Info == nil {
		e.OutErr(c, e.ERR_TOKEN_AUTH, errors.New("无效token"))
		return
	}
	signUser.Profile, err = db.UserProfileFindByArkID(db.DBs[c.GetString("mid")], utils.IntToStr(arkIdUser.UserID))
	if err != nil {
		e.OutErr(c, e.ERR_TOKEN_AUTH, err)
		return
	}
	c.Set("user", signUser)
	c.Next()
}
