import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";
import { encodeReferralCode } from "@/lib/referral";

export async function GET(req: NextRequest) {
  const jwtPayload = await requireAuth(req);
  if (!jwtPayload) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const userId = jwtPayload.userId;

    const [totalReferrals, upgradedCount, earnings] = await Promise.all([
      prisma.referral.count({
        where: { referrerId: userId },
      }),
      prisma.referral.count({
        where: { referrerId: userId, status: "upgraded" },
      }),
      prisma.referral.aggregate({
        where: { referrerId: userId },
        _sum: { rewardFlh: true },
      }),
    ]);

    const referralCode = encodeReferralCode(userId);

    return NextResponse.json({
      totalReferrals,
      upgradedCount,
      totalEarned: earnings._sum.rewardFlh || 0,
      referralCode,
      shareLink: `${process.env.NEXT_PUBLIC_APP_URL || "https://falahos.my/mobile"}/auth?ref=${referralCode}`,
    });
  } catch (error) {
    console.error("Referral stats error:", error);
    return NextResponse.json(
      { error: "Failed to get referral stats" },
      { status: 500 }
    );
  }
}
