package wechat

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/log"
	"fmt"
)

type QRCode4BindCache struct {
	UserId int64
	Status int
}

const (
	BIND_STATUS_UNBIND  = 0
	BIND_STATUS_SCANNED = 1
	BIND_STATUS_BOUND   = 2
	BIND_STATUS_EXPIRED = 9
)

const (
	BIND_REPLY_SUCCESS             = "扫码成功，您可以使用OpenI启智社区算力环境。"
	BIND_REPLY_WECHAT_ACCOUNT_USED = "认证失败，您的微信号已绑定其他启智账号"
	BIND_REPLY_OPENI_ACCOUNT_USED  = "认证失败，您待认证的启智账号已绑定其他微信号"
	BIND_REPLY_FAILED_DEFAULT      = "微信认证失败"
)

type WechatBindError struct {
	Reply string
}

func NewWechatBindError(reply string) WechatBindError {
	return WechatBindError{Reply: reply}
}

func (err WechatBindError) Error() string {
	return fmt.Sprint("wechat bind error,reply=%s", err.Reply)
}

func BindWechat(userId int64, wechatOpenId string) error {
	if !IsWechatAccountUsed(userId, wechatOpenId) {
		log.Error("bind wechat failed, because user use wrong wechat account to bind,userId=%d  wechatOpenId=%s", userId, wechatOpenId)
		return NewWechatBindError(BIND_REPLY_WECHAT_ACCOUNT_USED)
	}
	if !IsUserAvailableForWechatBind(userId, wechatOpenId) {
		log.Error("openI account has been used,userId=%d  wechatOpenId=%s", userId, wechatOpenId)
		return NewWechatBindError(BIND_REPLY_OPENI_ACCOUNT_USED)
	}
	return models.BindWechatOpenId(userId, wechatOpenId)
}

func UnbindWechat(userId int64, oldWechatOpenId string) error {
	return models.UnbindWechatOpenId(userId, oldWechatOpenId)
}

//IsUserAvailableForWechatBind  if user has bound wechat and the bound openId is not the given wechatOpenId,return false
//otherwise,return true
func IsUserAvailableForWechatBind(userId int64, wechatOpenId string) bool {
	currentOpenId := models.GetUserWechatOpenId(userId)
	return currentOpenId == "" || currentOpenId == wechatOpenId
}

//IsWechatAccountUsed  if wechat account used by another account,return false
//if wechat account not used or used by the given user,return true
func IsWechatAccountUsed(userId int64, wechatOpenId string) bool {
	user := models.GetUserByWechatOpenId(wechatOpenId)
	if user != nil && user.WechatOpenId != "" && user.ID != userId {
		return false
	}
	return true
}
