/**
 * GET /api/referrals — List all referrals (admin view).
 */

import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import * as growthClient from '@/lib/growth-client';
export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    const url = new URL(req.url);
    const limit = parseInt(url.searchParams.get('limit') ?? '100', 10);
    const offset = parseInt(url.searchParams.get('offset') ?? '0', 10);
    const mode = url.searchParams.get('mode');
    if (mode === 'summary') {
      const stats = await growthClient.getReferralStats();
      return NextResponse.json(stats);
    }
    const [listRes, stats] = await Promise.all([
      growthClient.listReferrals(limit, offset),
      growthClient.getReferralStats(),
    ]);
    return NextResponse.json({ referrals: listRes.referrals, stats });
  } catch (error) {
    logError('List referrals error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
