import { NextRequest, NextResponse } from 'next/server';
import { eraseTelemetryUser } 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 ', '') ?? '';
}

/**
 * GDPR erasure — delete all telemetry events for a given userId.
 * POST body: { userId: string }
 */
export async function POST(req: NextRequest) {
  const jwt = getJwt(req);
  if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const { userId } = await req.json();
    if (!userId || typeof userId !== 'string') {
      return NextResponse.json({ error: 'userId required' }, { status: 400 });
    }
    const result = await eraseTelemetryUser(jwt, userId);
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}
