package user

import (
	"bdrp-server/app/main/model"
	"bdrp-server/common/xerr"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"github.com/pkg/errors"

	"bdrp-server/app/main/api/internal/svc"
	"bdrp-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WxH5AuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWxH5AuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxH5AuthLogic {
	return &WxH5AuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthResp, err error) {
	// Step 1: 使用code获取access_token
	accessTokenResp, err := l.GetAccessToken(req.Code)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取access_token失败: %v", err)
	}

	// Step 2: 查找用户授权信息
	userAuth, findErr := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5OpenID, accessTokenResp.Openid)
	if findErr != nil && !errors.Is(findErr, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户授权失败: %v", findErr)
	}

	// Step 3: 处理用户信息
	var userID int64
	var userType int64
	if userAuth != nil {
		// 已存在用户，直接登录（被封禁用户禁止登录）
		user, err := l.svcCtx.UserModel.FindOne(l.ctx, userAuth.UserId)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户失败: %v", err)
		}
		if user.Disable == 1 {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
		}
		userID = userAuth.UserId
		userType = model.UserTypeNormal
	} else {
		// 检查临时用户表
		userTemp, err := l.svcCtx.UserTempModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5OpenID, accessTokenResp.Openid)
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户临时信息失败: %v", err)
		}

		if userTemp == nil {
			// 创建临时用户记录
			userTemp = &model.UserTemp{
				AuthType: model.UserAuthTypeWxh5OpenID,
				AuthKey:  accessTokenResp.Openid,
			}
			result, err := l.svcCtx.UserTempModel.Insert(l.ctx, nil, userTemp)
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建临时用户信息失败: %v", err)
			}
			userID, err = result.LastInsertId()
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的临时用户ID失败: %v", err)
			}
		} else {
			userID = userTemp.Id
		}
		userType = model.UserTypeTemp
	}

	// Step 4: 生成JWT Token
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, userType)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成JWT token失败: %v", err)
	}

	// Step 5: 返回登录结果
	now := time.Now().Unix()
	return &types.WXH5AuthResp{
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

type AccessTokenResp struct {
	AccessToken string `json:"access_token"`
	Openid      string `json:"openid"`
	ErrCode     int    `json:"errcode,omitempty"`
	ErrMsg      string `json:"errmsg,omitempty"`
}

// GetAccessToken 通过code获取access_token
func (l *WxH5AuthLogic) GetAccessToken(code string) (*AccessTokenResp, error) {
	appID := l.svcCtx.Config.WechatH5.AppID
	appSecret := l.svcCtx.Config.WechatH5.AppSecret

	url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
	const (
		maxRetryTimes = 3
		httpTimeout   = 5 * time.Second
		retryDelay    = 100 * time.Millisecond
	)

	client := &http.Client{Timeout: httpTimeout}
	var lastErr error

	for attempt := 1; attempt <= maxRetryTimes; attempt++ {
		resp, err := client.Get(url)
		if err != nil {
			lastErr = err
		} else {
			body, readErr := io.ReadAll(resp.Body)
			resp.Body.Close()
			if readErr != nil {
				lastErr = readErr
			} else {
				var accessTokenResp AccessTokenResp
				if unmarshalErr := json.Unmarshal(body, &accessTokenResp); unmarshalErr != nil {
					lastErr = unmarshalErr
				} else {
					if accessTokenResp.ErrCode != 0 {
						return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
							"微信接口返回错误: errcode=%d, errmsg=%s",
							accessTokenResp.ErrCode, accessTokenResp.ErrMsg)
					}
					if accessTokenResp.AccessToken == "" || accessTokenResp.Openid == "" {
						return nil, errors.New("微信接口返回数据不完整")
					}
					return &accessTokenResp, nil
				}
			}
		}

		if attempt < maxRetryTimes {
			time.Sleep(time.Duration(attempt) * retryDelay)
		}
	}

	return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "请求微信access_token接口失败(重试%d次): %v", maxRetryTimes, lastErr)
}
