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

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

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

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

func (l *StartBrandScanJobLogic) StartBrandScanJob(req *types.StartBrandScanJobHandlerReq) (resp *types.StartBrandScanJobData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.Brand.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}
	graph, err := l.svcCtx.KnowledgeGraph.Get(l.ctx, tenantID, uid, req.ID)
	if err != nil {
		return nil, err
	}

	selected := 0
	for _, node := range graph.Nodes {
		if node.SelectedForScan {
			selected++
		}
	}
	nodeIDs := []string{}
	graphID := graph.ID
	for _, id := range req.NodeIDs {
		id = strings.TrimSpace(id)
		if id != "" {
			nodeIDs = append(nodeIDs, id)
		}
	}
	if strings.TrimSpace(req.GraphID) != "" {
		graphID = strings.TrimSpace(req.GraphID)
	}
	dualTrack := true
	if len(nodeIDs) == 0 && selected == 0 {
		return nil, app.For(code.Brand).InputMissingRequired("請先在研究頁勾選至少一個節點")
	}

	research, err := l.svcCtx.Placement.ResearchSettings(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	memberCtx, err := l.svcCtx.ThreadsAccount.ResolveMemberPlacementContext(l.ctx, tenantID, uid, research)
	if err != nil {
		return nil, err
	}
	if !memberCtx.AllowsBrave && !memberCtx.AllowsThreadsAPI && !memberCtx.AllowsCrawler {
		return nil, app.For(code.Setting).InputMissingRequired("目前連線模式無法海巡，請確認 Threads API、Brave 或 Chrome Session")
	}
	if memberCtx.AllowsBrave && strings.TrimSpace(research.BraveAPIKey) == "" {
		return nil, app.For(code.Setting).InputMissingRequired("請在設定頁設定 Brave Search API key（跟隨此登入帳號）")
	}
	if memberCtx.DevMode && !memberCtx.BrowserConnected {
		return nil, app.For(code.Setting).InputMissingRequired("開發模式需先同步 Chrome Session")
	}

	payload := map[string]any{
		"brand_id":   req.ID,
		"graph_id":   graphID,
		"dual_track": dualTrack,
		"node_ids":   nodeIDs,
	}
	for key, value := range memberCtx.PayloadFields() {
		payload[key] = value
	}

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

	return &types.StartBrandScanJobData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "雙軌海巡已在背景執行，完成後可到獲客台查看貼文",
	}, nil
}
