import { NextRequest, NextResponse } from 'next/server';
import { queryTelemetryEvents, queryTelemetryClusters } from '@/lib/platform-client';

function getJwt(req: NextRequest): string {
  const cookie = req.headers.get('cookie') ?? '';
  const match = cookie.match(/(?:^|;\s*)token=([^;]+)/);
  if (match) return match[1];
  return req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
}

export async function GET(req: NextRequest) {
  const jwt = getJwt(req);
  if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const view = searchParams.get('view') || 'events';

  try {
    const filters: Record<string, string> = {};
    for (const [key, value] of searchParams.entries()) {
      if (key !== 'view' && value) filters[key] = value;
    }

    if (view === 'clusters') {
      const result = await queryTelemetryClusters(jwt, filters);
      return NextResponse.json(result);
    }

    const result = await queryTelemetryEvents(jwt, filters);
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}
