// 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"
	libkg "haixun-backend/internal/library/knowledge"
	"haixun-backend/internal/library/placement"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *ExpandKnowledgeGraphLogic) ExpandKnowledgeGraph(req *types.ExpandKnowledgeGraphHandlerReq) (resp *types.ExpandKnowledgeGraphData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	seed := strings.TrimSpace(req.SeedQuery)
	supplemental := req.Supplemental
	if seed == "" {
		return nil, app.For(code.Brand).InputMissingRequired("seed_query is required")
	}

	if _, err := l.svcCtx.Brand.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}

	research, err := l.svcCtx.Placement.ResearchSettings(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	expandStrategy := placement.EffectiveExpandStrategy(research)
	if supplemental && placement.WebSearchAvailable(research) {
		expandStrategy = libkg.ExpandStrategyBrave
	}
	memberCtx, err := l.svcCtx.ThreadsAccount.ResolveMemberPlacementContext(l.ctx, tenantID, uid, research)
	if err != nil {
		return nil, err
	}

	payload := map[string]any{
		"brand_id":        req.ID,
		"seed_query":      seed,
		"supplemental":    supplemental,
		"regenerate_map":  req.RegenerateMap,
		"expand_strategy": expandStrategy.String(),
	}
	for key, value := range memberCtx.PayloadFields() {
		payload[key] = value
	}

	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "expand-graph",
		Scope:        "brand",
		ScopeID:      req.ID,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}

	message := "研究地圖產生中，完成後可檢視延伸知識與參考連結"

	return &types.ExpandKnowledgeGraphData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: message,
	}, nil
}
