package admin_platform_user

import (
	"context"
	"database/sql"

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

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

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

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

func (l *AdminCreatePlatformUserLogic) AdminCreatePlatformUser(req *types.AdminCreatePlatformUserReq) (resp *types.AdminCreatePlatformUserResp, err error) {
	// 加密手机号
	key := l.svcCtx.Config.Encrypt.SecretKey
	encryptedMobile, err := crypto.EncryptMobile(req.Mobile, key)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建平台用户, 加密手机号失败: %v", err)
	}

	// 校验手机号唯一性（按加密后值）
	_, err = l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
	if err == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机号已存在: %s", req.Mobile)
	}
	if err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询手机号失败: %v", err)
	}

	// 处理密码（如提供则加密存储）
	var password sql.NullString
	if req.Password != "" {
		hashedPassword, hashErr := crypto.PasswordHash(req.Password)
		if hashErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建平台用户, 加密密码失败: %v", hashErr)
		}
		password = sql.NullString{String: hashedPassword, Valid: true}
	}

	user := &model.User{
		Id:       uuid.NewString(),
		Mobile:   sql.NullString{String: encryptedMobile, Valid: true},
		Password: password,
		Nickname: sql.NullString{String: req.Nickname, Valid: req.Nickname != ""},
		Info:     req.Info,
		Inside:   req.Inside,
	}
	_, err = l.svcCtx.UserModel.Insert(l.ctx, nil, user)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建用户失败: %v", err)
	}
	resp = &types.AdminCreatePlatformUserResp{Id: user.Id}
	return resp, nil
}
