import { NextRequest, NextResponse } from 'next/server';
import { updateTelemetryPolicy, deleteTelemetryPolicy } 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 PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const jwt = getJwt(req);
  if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const { id } = await params;
    const body = await req.json();
    const result = await updateTelemetryPolicy(jwt, id, body);
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const jwt = getJwt(req);
  if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const { id } = await params;
    const result = await deleteTelemetryPolicy(jwt, id);
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}
