/**
 * Referral Stats API
 * GET - Get aggregated referral statistics
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { convexQuery } from "@/lib/convex-client";

const log = logger.scope("ReferralStatsAPI");

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const result = await convexQuery(
      "reviews/referral_queries:getReferralStats",
      {
        userId: user.userId,
      },
    );

    if (result) {
      return NextResponse.json({ ...result, success: true });
    }

    // Fallback: return zeroed stats when Convex function is not yet available
    return NextResponse.json({
      totalCodes: 0,
      totalUses: 0,
      totalConversions: 0,
      totalRewards: 0,
      conversionRate: 0,
      success: true,
    });
  } catch (error) {
    log.error("Failed to get referral stats", error);

    // Graceful degradation: return zero stats instead of 500
    return NextResponse.json({
      totalCodes: 0,
      totalUses: 0,
      totalConversions: 0,
      totalRewards: 0,
      conversionRate: 0,
      success: true,
    });
  }
}
