import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import {
  revokeToken as revokeTokenViaService,
  deleteToken as deleteTokenViaService,
} 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 PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const jwt = getJwt(req);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const { id } = await params;
    const result = await revokeTokenViaService(jwt, id);
    return NextResponse.json(result);
  } catch (error) {
    logError('Patch token error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const jwt = getJwt(req);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const { id } = await params;
    const result = await deleteTokenViaService(jwt, id);
    return NextResponse.json(result);
  } catch (error) {
    logError('Delete token error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
