package radar

import (
	"context"

	"apps/backend/internal/logic/radarmap"
	"apps/backend/internal/module/radar/domain"
	radaruc "apps/backend/internal/module/radar/usecase"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GetRadarTodayLogic) GetRadarToday(req *types.RadarTodayReq) (*types.RadarTodayData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	filter := domain.OpportunityListFilter{}
	if req != nil {
		filter.BrandID, filter.ProductID, filter.FitBand = req.BrandId, req.ProductId, req.FitBand
	}
	t, err := l.svcCtx.Radar.GetTodayFiltered(l.ctx, uid, filter)
	if err != nil {
		return nil, err
	}
	return &types.RadarTodayData{
		Stats:          types.RadarTodayStats{Total: t.Stats.Total, High: t.Stats.High, Mid: t.Stats.Mid, Low: t.Stats.Low},
		High:           mapTodayCards(t.High),
		Mid:            mapTodayCards(t.Mid),
		Low:            mapTodayCards(t.Low),
		TruncatedCount: t.TruncatedCount,
		LastSweptAt:    t.LastSweptAt,
		EmptyReason:    t.EmptyReason,
		EmptyHint:      t.EmptyHint,
	}, nil
}

func mapTodayCards(cards []radaruc.TodayOpportunity) []types.OpportunityPublic {
	out := make([]types.OpportunityPublic, 0, len(cards))
	for _, c := range cards {
		if c.Opportunity == nil {
			continue
		}
		p := radarmap.Opportunity(c.Opportunity)
		if p == nil {
			continue
		}
		if c.DefaultReply != nil {
			p.DefaultReply = radarmap.Reply(c.DefaultReply)
		}
		out = append(out, *p)
	}
	return out
}
