package copy_mission

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/job/domain/enum"
	domrepo "haixun-backend/internal/model/job/domain/repository"
	"haixun-backend/internal/svc"
)

func ensureNoActiveMatrixJob(ctx context.Context, svcCtx *svc.ServiceContext, missionID string) error {
	if svcCtx == nil || svcCtx.Job == nil {
		return nil
	}
	missionID = strings.TrimSpace(missionID)
	if missionID == "" {
		return nil
	}
	runs, _, _, _, _, err := svcCtx.Job.ListRuns(ctx, domrepo.RunListFilter{
		Scope:   "copy_mission",
		ScopeID: missionID,
		Statuses: []enum.RunStatus{
			enum.RunStatusPending,
			enum.RunStatusQueued,
			enum.RunStatusRunning,
			enum.RunStatusWaitingWorker,
			enum.RunStatusCancelRequested,
		},
	}, 1, 20)
	if err != nil {
		return err
	}
	for _, run := range runs {
		if run != nil && run.TemplateType == "generate-copy-matrix" {
			return app.For(code.Job).ResInvalidState("內容矩陣背景任務進行中，請稍後再試")
		}
	}
	return nil
}