package user

import (
	"context"

	"sundynix-micro-go/app/system/api/internal/svc"
	"sundynix-micro-go/app/system/api/internal/types"
	"sundynix-micro-go/app/system/rpc/system"

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

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

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

func (l *CreateUserLogic) CreateUser(req *types.UserCreateReq) error {
	resp, err := l.svcCtx.SystemRpc.CreateUser(l.ctx, &system.CreateUserReq{
		Name:     req.Name,
		Account:  req.Account,
		Password: req.Password,
		Phone:    req.Phone,
	})
	if err != nil {
		return err
	}
	// 创建完成后立即绑定角色
	if len(req.RoleIds) > 0 && resp != nil {
		_, err = l.svcCtx.SystemRpc.AssignUserRoles(l.ctx, &system.AssignUserRolesReq{
			UserId:  resp.User.Id,
			RoleIds: req.RoleIds,
		})
	}
	return err
}
