package radar

import (
	"context"

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

	"time"

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

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

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

func (l *ListOpportunitiesLogic) ListOpportunities(req *types.ListOpportunitiesReq) (*types.OpportunityListData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	postedFrom, postedTo := req.From, req.To
	now := domain.NowNano()
	if req.TimeScope == "today" {
		postedFrom, postedTo = domain.LocalDayBounds(now, domain.DisplayLocation())
	} else if req.TimeScope == "7d" {
		postedFrom, postedTo = now-7*int64(24*time.Hour), 0
	}
	list, total, err := l.svcCtx.Radar.ListOpportunities(l.ctx, uid, domain.OpportunityListFilter{
		Band: req.Band, Status: req.Status, WatchID: req.WatchId,
		BrandID: req.BrandId, ProductID: req.ProductId, FitBand: req.FitBand, MatchState: req.MatchState, Sort: req.Sort,
		CreatedFrom: req.From, CreatedTo: req.To, PostedFrom: postedFrom, PostedTo: postedTo, Page: req.Page, PageSize: req.PageSize,
		ReviewState: req.ReviewState, TimeScope: req.TimeScope, PriorityBand: req.PriorityBand,
	})
	if err != nil {
		return nil, err
	}
	return &types.OpportunityListData{List: radarmap.OpportunityList(list), Pagination: radarmap.Pagination(req.Page, req.PageSize, total)}, nil
}
