package outcomes

import (
	"context"
	"fmt"
	"time"

	"apps/backend/internal/logic/growthmap"
	"apps/backend/internal/middleware"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GetOutcomeSummaryLogic) GetOutcomeSummary(req *types.OutcomeSummaryReq) (*types.OutcomeSummaryData, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	from, to := req.From, req.To
	if from == 0 && to == 0 {
		to = time.Now().UTC().UnixNano()
		if req.Range == "month" {
			from = to - int64(30*24*time.Hour)
		} else {
			from = to - int64(7*24*time.Hour)
		}
	}
	sum, err := l.svcCtx.Growth.Summary(l.ctx, uid, from, to)
	if err != nil {
		return nil, err
	}
	return growthmap.Summary(sum), nil
}
