package persona

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"
)

type StartPersonaViralScanJobLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStartPersonaViralScanJobLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StartPersonaViralScanJobLogic {
	return &StartPersonaViralScanJobLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *StartPersonaViralScanJobLogic) StartPersonaViralScanJob(
	req *types.StartPersonaViralScanJobHandlerReq,
) (*types.StartPersonaViralScanJobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.ID)
	if personaID == "" {
		return nil, app.For(code.Persona).InputMissingRequired("persona id is required")
	}
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}

	keywords := []string{}
	if req.StartPersonaViralScanJobReq.Keywords != nil {
		for _, kw := range req.StartPersonaViralScanJobReq.Keywords {
			kw = strings.TrimSpace(kw)
			if kw != "" {
				keywords = append(keywords, kw)
			}
		}
	}

	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.HasDiscoverPath() {
		return nil, app.For(code.Setting).InputMissingRequired("爆款掃描需要 Threads API、Chrome Session 或 Web Search API（請檢查連線模式與搜尋來源）")
	}

	payload := map[string]any{
		"persona_id": personaID,
		"keywords":   keywords,
		"bootstrap":  true,
	}
	for key, value := range memberCtx.PayloadFields() {
		payload[key] = value
	}

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

	return &types.StartPersonaViralScanJobData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "爆款掃描已在背景執行，完成後可產出仿寫草稿",
	}, nil
}
