package copy_mission

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 StartCopyMissionAnalyzeJobLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *StartCopyMissionAnalyzeJobLogic) StartCopyMissionAnalyzeJob(
	req *types.CopyMissionPath,
) (*types.StartCopyMissionAnalyzeJobData, 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
	}
	if _, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID); err != nil {
		return nil, err
	}

	payload := map[string]any{
		"tenant_id":       tenantID,
		"owner_uid":       uid,
		"persona_id":      personaID,
		"copy_mission_id": missionID,
	}
	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "analyze-copy-mission",
		Scope:        "copy_mission",
		ScopeID:      missionID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	if run == nil {
		return nil, app.For(code.Job).ResInvalidState("analyze job not created")
	}
	return &types.StartCopyMissionAnalyzeJobData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "受眾與研究地圖分析已在背景執行，完成後可微調標籤並開始海巡",
	}, nil
}
