package admin_platform_user

import (
	"context"
	"database/sql"

	"in-server/app/main/api/internal/svc"
	"in-server/app/main/api/internal/types"
	"in-server/common/xerr"
	"in-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), "用户不存在: %s, 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 {
		// 密码为空字符串时不修改密码，避免误清空
		if *req.Password != "" {
			hashedPassword, hashErr := crypto.PasswordHash(*req.Password)
			if hashErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "更新用户密码失败: %v", hashErr)
			}
			user.Password = sql.NullString{String: hashedPassword, Valid: true}
		}
	}
	_, 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
}
