import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import {
  listTokens as listTokensViaService,
  createToken as createTokenViaService,
} 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) {
  try {
    const jwt = getJwt(req);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const result = await listTokensViaService(jwt);
    return NextResponse.json(result);
  } catch (error) {
    logError('List tokens error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const jwt = getJwt(req);
    if (!jwt) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const { name, scopes, expiresInDays } = await req.json();
    if (!name) {
      return NextResponse.json({ error: 'name is required' }, { status: 400 });
    }
    const result = await createTokenViaService(jwt, { name, scopes, expiresInDays });
    return NextResponse.json(result, { status: 201 });
  } catch (error) {
    logError('Create token error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
