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

export const dynamic = 'force-dynamic';

const NBA_SERVICE = process.env.NBA_SERVICE_URL || process.env.NEXT_PUBLIC_NBA_SERVICE_URL || 'http://localhost:8000';
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000';

interface Player {
  id: string;
  full_name: string;
  team?: string;
  position?: string;
}

export async function GET(req: NextRequest) {
  const sport = (req.nextUrl.searchParams.get('sport') || 'NBA').toUpperCase();
  const q = (req.nextUrl.searchParams.get('q') || '').trim();
  const gameId = req.nextUrl.searchParams.get('game_id') || '';

  if (q.length < 2) return NextResponse.json({ players: [] });

  try {
    // Session 60 (night2/E, audit 4.1) — Express is the canonical resolver
    // for EVERY sport now (nameKey fuzzy match; MLB = full statsapi list,
    // others = the platform's cached names). The Python NBA service is a
    // best-effort second try only when the canonical index has nothing.
    const url = `${BACKEND_URL}/api/players/search?sport=${encodeURIComponent(sport)}&q=${encodeURIComponent(q)}${gameId ? `&game_id=${encodeURIComponent(gameId)}` : ''}`;

    let res = await fetch(url, { headers: { Accept: 'application/json' } });
    let data = res.ok ? await res.json().catch(() => ({})) : {};
    const canonical = Array.isArray((data as { players?: unknown[] }).players) ? (data as { players: unknown[] }).players : [];
    if (canonical.length === 0 && sport !== 'MLB') {
      res = await fetch(`${NBA_SERVICE}/players/search?name=${encodeURIComponent(q)}`, { headers: { Accept: 'application/json' } }).catch(() => new Response(null, { status: 502 }));
      data = res.ok ? await res.json().catch(() => ({})) : {};
    }
    const rawPlayers: unknown[] = Array.isArray((data as { results?: unknown[] }).results)
      ? (data as { results: unknown[] }).results
      : Array.isArray((data as { players?: unknown[] }).players)
        ? (data as { players: unknown[] }).players
        : [];

    const players: Player[] = rawPlayers.slice(0, 12).map((p) => {
      const obj = (p && typeof p === 'object' ? p : {}) as Record<string, unknown>;
      return {
        id: String(obj.id ?? obj.player_id ?? obj.full_name ?? Math.random()),
        full_name: String(obj.full_name ?? obj.name ?? ''),
        team: typeof obj.team === 'string' ? obj.team : undefined,
        position: typeof obj.position === 'string' ? obj.position : undefined,
      };
    }).filter((p) => p.full_name);

    return NextResponse.json({ players });
  } catch {
    return NextResponse.json({ players: [] });
  }
}
