package usage

import (
	"context"

	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GetTenantUsageSummaryLogic) GetTenantUsageSummary(req *types.UsageTenantSummaryReq) (*types.UsageTenantSummaryData, error) {
	if l.svcCtx.Usage == nil {
		return nil, response.Biz(503, 503001, "usage not configured")
	}
	// AdminAuth on route
	ten, err := l.svcCtx.Usage.TenantSummary(l.ctx, req.MonthKey)
	if err != nil {
		return nil, err
	}
	members := make([]types.UsageTenantRow, 0, len(ten.Members))
	for _, m := range ten.Members {
		members = append(members, types.UsageTenantRow{
			Uid: m.UID, PlanId: m.PlanID, Unlimited: m.Unlimited,
			PlatformCreditsUsed: m.PlatformCreditsUsed, ByokCallCount: m.ByokCallCount,
		})
	}
	return &types.UsageTenantSummaryData{
		MonthKey: ten.MonthKey, PlatformCreditsUsed: ten.PlatformCreditsUsed,
		ByokCallCount: ten.ByokCallCount, Members: members,
	}, nil
}
