package copy_mission

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	libviral "haixun-backend/internal/library/viral"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *StartCopyMissionScanJobLogic) StartCopyMissionScanJob(
	req *types.CopyMissionPath,
) (*types.StartCopyMissionScanJobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.PersonaID)
	missionID := strings.TrimSpace(req.ID)
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}
	mission, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID)
	if err != nil {
		return nil, err
	}
	if mission.ResearchMap.AudienceSummary == "" && len(mission.ResearchMap.SuggestedTags) == 0 {
		return nil, app.For(code.Persona).InputMissingRequired("請先產生研究地圖")
	}
	if len(mission.SelectedTags) == 0 {
		return nil, app.For(code.Persona).InputMissingRequired("請至少勾選一個搜尋標籤")
	}
	if len(mission.SelectedTags) > libviral.MaxScanTags {
		return nil, app.For(code.Persona).InputMissingRequired("搜尋標籤最多 6 個，請減少勾選以節省搜尋配額")
	}

	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（請檢查連線模式與搜尋來源）")
	}

	if err := l.svcCtx.ScanPost.ClearCopyMissionViralScan(l.ctx, tenantID, uid, personaID, missionID); err != nil {
		return nil, err
	}
	if err := l.svcCtx.CopyDraft.ClearByMission(l.ctx, tenantID, uid, personaID, missionID); err != nil {
		return nil, err
	}

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

	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "scan-viral",
		Scope:        "copy_mission",
		ScopeID:      missionID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	return &types.StartCopyMissionScanJobData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "已清除舊爆款與產文草稿，海巡已在背景執行",
	}, nil
}
