package brand

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	liboutreach "haixun-backend/internal/library/outreach"
	"haixun-backend/internal/library/threadspost"
	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 UpdateOutreachDraftLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *UpdateOutreachDraftLogic) UpdateOutreachDraft(req *types.UpdateOutreachDraftHandlerReq) (*types.GenerateOutreachDraftsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	draftID := strings.TrimSpace(req.DraftID)
	if draftID == "" {
		return nil, app.For(code.Brand).InputMissingRequired("draft_id is required")
	}
	text := liboutreach.NormalizeDraftText(req.Text)
	if text == "" {
		return nil, app.For(code.Brand).InputMissingRequired("text is required")
	}
	if err := threadspost.ValidateReply(text); err != nil {
		return nil, app.For(code.Brand).InputInvalidFormat(err.Error())
	}
	if req.DraftIndex < 0 {
		return nil, app.For(code.Brand).InputInvalidFormat("draft_index must be >= 0")
	}

	if _, err := l.svcCtx.Brand.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}

	updated, err := l.svcCtx.OutreachDraft.UpdateDraftItem(l.ctx, outreachusecase.UpdateDraftItemRequest{
		TenantID:   tenantID,
		OwnerUID:   uid,
		BrandID:    req.ID,
		DraftID:    draftID,
		DraftIndex: req.DraftIndex,
		Text:       text,
	})
	if err != nil {
		return nil, err
	}
	return toOutreachDraftData(updated), nil
}
