// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package persona

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"

	"github.com/zeromicro/go-zero/core/logx"
)

type StartPersonaStyleAnalysisLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStartPersonaStyleAnalysisLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StartPersonaStyleAnalysisLogic {
	return &StartPersonaStyleAnalysisLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StartPersonaStyleAnalysisLogic) StartPersonaStyleAnalysis(req *types.StartPersonaStyleAnalysisHandlerReq) (resp *types.StartPersonaStyleAnalysisData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	username := ""
	if req != nil {
		username = strings.TrimPrefix(strings.TrimSpace(req.BenchmarkUsername), "@")
	}
	if username == "" {
		return nil, app.For(code.Persona).InputMissingRequired("benchmark_username is required")
	}

	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}
	activeAccountID := ""
	if member, err := l.svcCtx.Member.GetByUID(l.ctx, tenantID, uid); err == nil {
		activeAccountID = member.ActiveThreadsAccountID
	}

	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "style-8d",
		Scope:        "persona",
		ScopeID:      req.ID,
		Payload: map[string]any{
			"persona_id":         req.ID,
			"benchmark_username": username,
			"tenant_id":          tenantID,
			"owner_uid":          uid,
			"threads_account_id": activeAccountID,
		},
	})
	if err != nil {
		return nil, err
	}

	return &types.StartPersonaStyleAnalysisData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "8D 分析已在背景執行，可自由切換頁面",
	}, nil
}
