import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000';

/**
 * Player intelligence proxy (Session 42). Forwards GET /api/stats/player/:name
 * to the Express stats route (which sanitizes the name + aggregates archetype /
 * props / VYNDR intelligence). Thin pass-through; preserves ?sport=.
 */
export async function GET(req: NextRequest, ctx: { params: Promise<{ name: string }> }) {
  const { name } = await ctx.params;
  const qs = req.nextUrl.search;
  try {
    const upstream = await fetch(`${BACKEND_URL}/api/stats/player/${encodeURIComponent(name)}${qs}`, {
      method: 'GET',
      headers: { Accept: 'application/json' },
    });
    const data = await upstream.json().catch(() => ({}));
    return NextResponse.json(data, { status: upstream.ok ? 200 : upstream.status });
  } catch {
    return NextResponse.json({ error: 'Player service is unreachable. Try again in a moment.' }, { status: 502 });
  }
}
