import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { computeRanking } from '@/lib/ranking';

export async function GET(req: NextRequest, { params }: { params: Promise<{ code: string }> }) {
  const { code } = await params;
  const db = getDb();
  const session = db.prepare('SELECT * FROM sessions WHERE code = ?').get(code) as any;
  if (!session) {
    return NextResponse.json({ error: 'Session nicht gefunden' }, { status: 404 });
  }

  const excludeRaw = req.nextUrl.searchParams.get('exclude');
  const excludeId = excludeRaw ? Number(excludeRaw) : undefined;

  const activeParticipantCount = (
    db.prepare('SELECT COUNT(*) as c FROM participants WHERE session_id = ? AND is_active = 1')
      .get(session.id) as { c: number }
  ).c;

  const ranking = computeRanking(db, session.id, excludeId).map((e) => ({
    ...e,
    city: session.city ?? null,
  }));

  return NextResponse.json({
    activeParticipantCount,
    city: session.city ?? null,
    ranking,
  });
}
