package allocagent

import (
	"context"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/zeromicro/go-zero/core/errorx"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

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

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

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

func (l *CreateAllocAgentLogic) CreateAllocAgent(req *types.AllocAgentInfo) (*types.BaseMsgResp, error) {
	if len(req.Agents) == 0 {
		return nil, errorx.NewInvalidArgumentError("智能体ID不能为空")
	}
	if req.OrganizationId == nil && req.UserId == nil {
		return nil, errorx.NewInvalidArgumentError("租户ID和用户ID不能都为空")
	}

	_, err := l.svcCtx.DB.AllocAgent.Create().
		SetNotNilUserID(req.UserId).
		SetNotNilOrganizationID(req.OrganizationId).
		SetNotNilAgents(req.Agents).
		SetNotNilStatus(tea.Int(1)).
		Save(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
}
