package admin_user

import (
	"context"

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

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

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

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

func (l *AdminCreateUserLogic) AdminCreateUser(req *types.AdminCreateUserReq) (resp *types.AdminCreateUserResp, err error) {
	// 检查用户名是否已存在
	exists, err := l.svcCtx.AdminUserModel.FindOneByUsername(l.ctx, req.Username)
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建用户失败: %v", err)
	}
	if exists != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("用户名已存在"), "创建用户失败")
	}
	password, err := crypto.PasswordHash("123456")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建用户失败, 加密密码失败: %v", err)
	}
	// 创建用户
	user := &model.AdminUser{
		Username: req.Username,
		Password: password, // 注意：实际应用中需要加密密码
		RealName: req.RealName,
		Status:   req.Status,
	}

	// 使用事务创建用户和关联角色
	err = l.svcCtx.AdminUserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 创建用户
		result, err := l.svcCtx.AdminUserModel.Insert(ctx, session, user)
		if err != nil {
			return err
		}
		userId, err := result.LastInsertId()
		if err != nil {
			return err
		}

		// 创建用户角色关联
		if len(req.RoleIds) > 0 {
			for _, roleId := range req.RoleIds {
				userRole := &model.AdminUserRole{
					UserId: userId,
					RoleId: roleId,
				}
				_, err = l.svcCtx.AdminUserRoleModel.Insert(ctx, session, userRole)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})

	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建用户失败: %v", err)
	}

	return &types.AdminCreateUserResp{
		Id: user.Id,
	}, nil
}
