package admin_platform_user

import (
	"context"
	"database/sql"

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

	"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) {
	// 校验手机号唯一性
	_, err = l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: req.Mobile, Valid: req.Mobile != ""})
	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)
	}

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