package invite

import (
	"context"
	"fmt"

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

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

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

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

func (l *GetMyInviteNetworkLogic) GetMyInviteNetwork() (resp *types.MyInviteNetworkData, err error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	net, err := l.svcCtx.Auth.GetMyNetwork(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	out := types.MyInviteNetworkFromUC(net)
	if l.svcCtx.Growth != nil && out != nil {
		planID := "free"
		if l.svcCtx.Usage != nil {
			if prefs, perr := l.svcCtx.Usage.GetPrefs(l.ctx, uid); perr == nil && prefs != nil {
				planID = prefs.PlanID
			}
		}
		total, month, cap, recent, rerr := l.svcCtx.Growth.InviteRewardsSummary(l.ctx, uid, planID)
		if rerr == nil {
			sum := &types.InviteRewardsSummary{
				TotalPoints: total,
				MonthPoints: month,
				MonthCap:    cap,
				Recent:      make([]types.InviteRewardPublic, 0, len(recent)),
			}
			for _, r := range recent {
				if r == nil {
					continue
				}
				sum.Recent = append(sum.Recent, types.InviteRewardPublic{
					Id: r.ID, InviteeUid: r.InviteeUID, PlanId: r.PlanID,
					Points: r.Points, Status: r.Status, CreatedAt: r.CreatedAt,
				})
			}
			out.Rewards = sum
		}
	}
	return out, nil
}
