package usecase

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/knowledge_graph/domain/entity"
)

func isGraphNotFound(err error) bool {
	if e := app.FromError(err); e != nil && e.Category() == code.ResNotFound {
		return true
	}
	return false
}

// loadTopicGraph resolves a placement-topic graph, including legacy brand-scoped graphs.
func (u *knowledgeGraphUseCase) loadTopicGraph(ctx context.Context, tenantID, ownerUID, topicID, brandID string) (*entity.Graph, error) {
	topicID = strings.TrimSpace(topicID)
	if topicID == "" {
		return nil, app.For(code.Brand).InputMissingRequired("topic id is required")
	}
	item, err := u.repo.FindByTopic(ctx, tenantID, ownerUID, topicID)
	if err != nil && !isGraphNotFound(err) {
		return nil, err
	}
	if item != nil {
		return item, nil
	}
	brandID = strings.TrimSpace(brandID)
	if brandID == "" {
		return nil, app.For(code.Brand).ResNotFound("knowledge graph not found")
	}
	legacy, legacyErr := u.repo.FindByBrand(ctx, tenantID, ownerUID, brandID)
	if legacyErr != nil {
		if isGraphNotFound(legacyErr) {
			return nil, app.For(code.Brand).ResNotFound("knowledge graph not found")
		}
		return nil, legacyErr
	}
	if legacy == nil {
		return nil, app.For(code.Brand).ResNotFound("knowledge graph not found")
	}
	legacyTopicID := strings.TrimSpace(legacy.TopicID)
	if legacyTopicID != "" && legacyTopicID != topicID {
		return nil, app.For(code.Brand).ResNotFound("knowledge graph not found")
	}
	if legacyTopicID == "" {
		if err := u.repo.AttachTopicID(ctx, tenantID, ownerUID, brandID, topicID); err != nil {
			return nil, err
		}
		legacy.TopicID = topicID
	}
	return legacy, nil
}
