package copy_mission

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/library/style8d"
	missionentity "haixun-backend/internal/model/copy_mission/domain/entity"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *StartCopyMissionMatrixJobLogic) StartCopyMissionMatrixJob(
	req *types.StartCopyMissionMatrixJobHandlerReq,
) (*types.StartCopyMissionMatrixJobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.PersonaID)
	missionID := strings.TrimSpace(req.ID)
	mission, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID)
	if err != nil {
		return nil, err
	}
	if mission.Status != string(missionentity.StatusScanned) &&
		mission.Status != string(missionentity.StatusDrafted) {
		return nil, app.For(code.Persona).ResInvalidState("請先完成海巡再產出內容矩陣")
	}
	if len(mission.SelectedTags) == 0 {
		return nil, app.For(code.Persona).InputMissingRequired("請先選擇海巡標籤")
	}

	persona, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID)
	if err != nil {
		return nil, err
	}
	if !style8d.HasReady8D(persona.Persona, persona.StyleProfile) {
		return nil, app.For(code.Persona).InputMissingRequired("請先完成人設 8D 對標分析")
	}

	count := req.Count
	if count <= 0 {
		count = 5
	}
	if count > 12 {
		count = 12
	}

	payload := map[string]any{
		"persona_id":      personaID,
		"copy_mission_id": missionID,
		"count":           count,
	}
	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "generate-copy-matrix",
		Scope:        "copy_mission",
		ScopeID:      missionID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	return &types.StartCopyMissionMatrixJobData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "內容矩陣產出已在背景執行",
	}, nil
}
