package radar

import (
	"context"
	"fmt"
	"strings"

	radardomain "apps/backend/internal/module/radar/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

// SuggestWatchTerms 只回建議，不寫入任何 watch：使用者要逐條決定採不採用（RW-03）。
func (l *SuggestWatchTermsLogic) SuggestWatchTerms(req *types.SuggestWatchTermsReq) (resp *types.WatchSuggestData, err error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	brandID := strings.TrimSpace(req.BrandId)
	productID := strings.TrimSpace(req.ProductId)
	if (brandID == "") != (productID == "") {
		return nil, fmt.Errorf("%w: brand_id and product_id must be provided together", radardomain.ErrValidation)
	}
	var list []radardomain.WatchTermSuggestion
	if brandID != "" {
		list, err = l.svcCtx.Radar.SuggestProductWatchTerms(l.ctx, uid, brandID, productID, req.Limit)
	} else {
		list, err = l.svcCtx.Radar.SuggestWatchTerms(l.ctx, uid, req.Limit)
	}
	if err != nil {
		return nil, err
	}
	out := make([]types.WatchTermSuggestion, 0, len(list))
	for _, s := range list {
		out = append(out, types.WatchTermSuggestion{Term: s.Term, Reason: s.Reason, Usage: s.Usage, BasisKind: s.BasisKind, BasisText: s.BasisText})
	}
	return &types.WatchSuggestData{List: out}, nil
}
