package user

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"ycc-server/app/main/api/internal/svc"
	"ycc-server/app/main/api/internal/types"
	"ycc-server/app/main/model"
	"ycc-server/common/xerr"

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

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

func NewWxMiniAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxMiniAuthLogic {
	return &WxMiniAuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}
func (l *WxMiniAuthLogic) WxMiniAuth(req *types.WXMiniAuthReq) (resp *types.WXMiniAuthResp, err error) {
	// 1. 获取session_key和openid
	sessionKeyResp, err := l.GetSessionKey(req.Code)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取session_key失败: %v", err)
	}

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

	// 3. 处理用户信息
	var userID int64
	var userType int64
	if userAuth != nil {
		// 已存在用户，直接登录
		userID = userAuth.UserId
		userType = model.UserTypeNormal
	} else {
		// 注册临时用户
		userTemp, err := l.svcCtx.UserTempModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxMiniOpenID, sessionKeyResp.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{}
			userTemp.AuthType = model.UserAuthTypeWxMiniOpenID
			userTemp.AuthKey = sessionKeyResp.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)
			}
			// 获取新创建的临时用户ID
			userID, err = result.LastInsertId()
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的临时用户ID失败: %v", err)
			}
		} else {
			// 使用已存在的临时用户ID
			userID = userTemp.Id
		}
		userType = model.UserTypeTemp
	}

	// 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)
	}

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

// SessionKeyResp 小程序登录返回结构
type SessionKeyResp struct {
	Openid     string `json:"openid"`
	SessionKey string `json:"session_key"`
	Unionid    string `json:"unionid,omitempty"`
	ErrCode    int    `json:"errcode,omitempty"`
	ErrMsg     string `json:"errmsg,omitempty"`
}

// GetSessionKey 通过code获取小程序的session_key和openid
func (l *WxMiniAuthLogic) GetSessionKey(code string) (*SessionKeyResp, error) {
	var appID string
	var appSecret string

	appID = l.svcCtx.Config.WechatMini.AppID
	appSecret = l.svcCtx.Config.WechatMini.AppSecret

	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		appID, appSecret, code)

	resp, err := http.Get(url)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取session_key失败: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "读取响应失败: %v", err)
	}

	var sessionKeyResp SessionKeyResp
	if err = json.Unmarshal(body, &sessionKeyResp); err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解析响应失败: %v", err)
	}

	// 检查微信返回的错误码
	if sessionKeyResp.ErrCode != 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
			"微信接口返回错误: errcode=%d, errmsg=%s",
			sessionKeyResp.ErrCode, sessionKeyResp.ErrMsg)
	}

	// 验证必要字段
	if sessionKeyResp.Openid == "" || sessionKeyResp.SessionKey == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
			"微信接口返回数据不完整: openid=%s, session_key=%s",
			sessionKeyResp.Openid, sessionKeyResp.SessionKey)
	}

	return &sessionKeyResp, nil
}
