package copy_mission

import (
	"context"
	"strings"

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

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

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

func (l *StartCopyMissionCopyDraftJobLogic) StartCopyMissionCopyDraftJob(
	req *types.StartCopyMissionCopyDraftJobHandlerReq,
) (*types.StartCopyMissionCopyDraftJobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.PersonaID)
	missionID := strings.TrimSpace(req.ID)
	scanPostID := strings.TrimSpace(req.ScanPostID)
	if scanPostID == "" {
		return nil, app.For(code.Persona).InputMissingRequired("scan_post_id is required")
	}

	if _, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID); err != nil {
		return nil, err
	}
	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 對標分析")
	}
	post, err := l.svcCtx.ScanPost.GetForPersona(l.ctx, tenantID, uid, personaID, scanPostID)
	if err != nil {
		return nil, err
	}
	if postMission := strings.TrimSpace(post.CopyMissionID); postMission != "" && postMission != missionID {
		return nil, app.For(code.Persona).ResInvalidState("爆款不屬於此任務")
	}

	payload := map[string]any{
		"persona_id":      personaID,
		"copy_mission_id": missionID,
		"scan_post_id":    scanPostID,
	}
	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "generate-copy-draft",
		Scope:        "copy_mission",
		ScopeID:      missionID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	return &types.StartCopyMissionCopyDraftJobData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "深仿寫已在背景執行",
	}, nil
}
