package placement_topic

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 PatchPlacementTopicGraphNodesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *PatchPlacementTopicGraphNodesLogic) PatchPlacementTopicGraphNodes(req *types.PatchPlacementTopicGraphNodesHandlerReq) (*types.KnowledgeGraphData, 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 := resolveScope(l.ctx, l.svcCtx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}
	updates := make([]kgusecase.NodeUpdate, 0, len(req.Updates))
	for _, item := range req.Updates {
		nodeID := strings.TrimSpace(item.NodeID)
		if nodeID == "" {
			continue
		}
		update := kgusecase.NodeUpdate{NodeID: nodeID}
		if item.SelectedForScan != nil {
			update.SelectedForScan = item.SelectedForScan
		}
		if item.RelevanceTags != nil {
			update.RelevanceTagsSet = true
			update.RelevanceTags = append([]string(nil), item.RelevanceTags...)
		}
		if item.RecencyTags != nil {
			update.RecencyTagsSet = true
			update.RecencyTags = append([]string(nil), item.RecencyTags...)
		}
		if update.SelectedForScan == nil && !update.RelevanceTagsSet && !update.RecencyTagsSet {
			return nil, app.For(code.Brand).InputMissingRequired("each update needs selected_for_scan or patrol tags")
		}
		updates = append(updates, update)
	}
	if len(updates) == 0 {
		return nil, app.For(code.Brand).InputMissingRequired("updates is required")
	}
	graph, err := l.svcCtx.KnowledgeGraph.UpdateNodes(l.ctx, kgusecase.UpdateNodesRequest{
		TenantID: tenantID,
		OwnerUID: uid,
		TopicID:  req.ID,
		Updates:  updates,
	})
	if err != nil {
		return nil, err
	}
	data := toKnowledgeGraphData(graph)
	return &data, nil
}
