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

package brand

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	liboutreach "haixun-backend/internal/library/outreach"
	outreachusecase "haixun-backend/internal/model/outreach_draft/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *GenerateOutreachDraftsLogic) GenerateOutreachDrafts(req *types.GenerateOutreachDraftsHandlerReq) (resp *types.GenerateOutreachDraftsData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	scanPostID := strings.TrimSpace(req.ScanPostID)
	if scanPostID == "" {
		return nil, app.For(code.Brand).InputMissingRequired("scan_post_id is required")
	}
	if strings.TrimSpace(req.VoicePersonaID) == "" {
		return nil, app.For(code.Brand).InputMissingRequired("voice_persona_id is required")
	}

	saved, err := liboutreach.GenerateDraft(l.ctx, outreachDepsFrom(l.svcCtx), liboutreach.GenerateDraftRequest{
		TenantID:       tenantID,
		OwnerUID:       uid,
		BrandID:        req.ID,
		TopicID:        strings.TrimSpace(req.TopicID),
		ScanPostID:     scanPostID,
		Count:          req.Count,
		VoicePersonaID: req.VoicePersonaID,
		ProductID:      req.ProductID,
		Regenerate:     req.Regenerate,
	})
	if err != nil {
		return nil, err
	}
	return toOutreachDraftData(saved), nil
}

func outreachDepsFrom(svcCtx *svc.ServiceContext) liboutreach.GenerateDraftDeps {
	return liboutreach.GenerateDraftDeps{
		Brand:          svcCtx.Brand,
		Persona:        svcCtx.Persona,
		ScanPost:       svcCtx.ScanPost,
		KnowledgeGraph: svcCtx.KnowledgeGraph,
		ThreadsAccount: svcCtx.ThreadsAccount,
		AI:             svcCtx.AI,
		OutreachDraft:  svcCtx.OutreachDraft,
	}
}

func toOutreachDraftData(saved *outreachusecase.DraftSummary) *types.GenerateOutreachDraftsData {
	if saved == nil {
		return nil
	}
	drafts := make([]types.OutreachDraftItemData, 0, len(saved.Drafts))
	for _, item := range saved.Drafts {
		drafts = append(drafts, types.OutreachDraftItemData{
			Text:      item.Text,
			Angle:     item.Angle,
			Rationale: item.Rationale,
		})
	}
	return &types.GenerateOutreachDraftsData{
		ID:         saved.ID,
		ScanPostID: saved.ScanPostID,
		Relevance:  saved.Relevance,
		Reason:     saved.Reason,
		Drafts:     drafts,
		CreateAt:   saved.CreateAt,
	}
}
