package admin_platform_user

import (
	"context"
	"database/sql"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

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

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

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

func (l *AdminUpdatePlatformUserLogic) AdminUpdatePlatformUser(req *types.AdminUpdatePlatformUserReq) (resp *types.AdminUpdatePlatformUserResp, err error) {
	user, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %d, err: %v", req.Id, err)
	}
	if req.Mobile != nil {
		key := l.svcCtx.Config.Encrypt.SecretKey
		EncryptMobile, err := crypto.EncryptMobile(*req.Mobile, key)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %v", err)
		}
		user.Mobile = sql.NullString{String: EncryptMobile, Valid: true}
	}
	if req.Nickname != nil {
		user.Nickname = sql.NullString{String: *req.Nickname, Valid: *req.Nickname != ""}
	}
	if req.Info != nil {
		user.Info = *req.Info
	}
	if req.Inside != nil {
		if *req.Inside != 1 && *req.Inside != 0 {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "内部用户状态错误: %d", *req.Inside)
		}
		user.Inside = *req.Inside
	}
	if req.Password != nil {
		user.Password = sql.NullString{String: *req.Password, Valid: *req.Password != ""}
	}
	_, err = l.svcCtx.UserModel.Update(l.ctx, nil, user)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新用户失败: %v", err)
	}
	resp = &types.AdminUpdatePlatformUserResp{Success: true}
	return resp, nil
}
