// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package brand

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	kgusecase "haixun-backend/internal/model/knowledge_graph/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *PatchKnowledgeGraphNodesLogic) PatchKnowledgeGraphNodes(req *types.PatchKnowledgeGraphNodesHandlerReq) (resp *types.KnowledgeGraphData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if len(req.Updates) == 0 {
		return nil, app.For(code.Brand).InputMissingRequired("updates is required")
	}
	if _, err := l.svcCtx.Brand.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}

	updates := make([]kgusecase.NodeSelectionUpdate, 0, len(req.Updates))
	for _, item := range req.Updates {
		updates = append(updates, kgusecase.NodeSelectionUpdate{
			NodeID:          strings.TrimSpace(item.NodeID),
			SelectedForScan: item.SelectedForScan,
		})
	}
	graph, err := l.svcCtx.KnowledgeGraph.UpdateNodeSelections(l.ctx, kgusecase.UpdateNodesRequest{
		TenantID: tenantID,
		OwnerUID: uid,
		BrandID:  req.ID,
		Updates:  updates,
	})
	if err != nil {
		return nil, err
	}
	data := toKnowledgeGraphData(graph)
	return &data, nil
}
