package sysUser

import (
	"context"

	"github.com/gogf/gf/v2/os/glog"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	v1 "kami/api/sysUser/v1"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
	"kami/utility/token"
)

func (c *ControllerV1) UserAdd(ctx context.Context, req *v1.UserAddReq) (res *v1.UserAddRes, err error) {
	if !token.IsFromIframe(ctx) {
		err = gerror.NewCode(gcode.CodeNotAuthorized)
		return
	}
	sysUserService := service.SysUser()
	// 解密
	userInfo, err := sysUserService.GetUserByUsername(ctx, req.Username)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeOperationFailed, err, "查询用户失败")
		return
	}
	if userInfo.Id != "" {
		err = gerror.NewCode(gcode.CodeInvalidParameter, "当前用户已存在")
		return
	}
	// 解密
	userId, err := sysUserService.Add(ctx, &model.UserAddInput{UserAddReq: req})
	err = errHandler.WrapError(ctx, gcode.CodeOperationFailed, err, "添加用户失败")
	_ = service.SysUserChannelConfig().Init(ctx, userId)
	for _, channelType := range req.ChannelList {
		if err2 := service.SysUserChannelConfig().AddOrUpdateOne(ctx, userId, channelType.ChannelName, channelType.Num); err2 != nil {
			glog.Error(ctx, "添加用户渠道配置失败", err2)
		}
	}
	// 添加用户钱包
	return
}
