import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getAuthenticatedAdmin } from '@/lib/admin-auth';
import { getRecentErrors, getErrorTotals, clearErrorLogs } from '@/lib/error-log';

export async function GET(req: NextRequest) {
  const admin = await getAuthenticatedAdmin();
  if (!admin) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

  const url = req.nextUrl;
  const source = url.searchParams.get('source') ?? undefined;
  const offset = Math.max(0, parseInt(url.searchParams.get('offset') ?? '0', 10) || 0);
  const limit = Math.min(Math.max(1, parseInt(url.searchParams.get('limit') ?? '50', 10) || 50), 200);

  const db = getDb();
  const { errors, total } = getRecentErrors(db, { limit, offset, source });
  const totals = getErrorTotals(db);
  return NextResponse.json({ errors, total, totals });
}

export async function DELETE() {
  const admin = await getAuthenticatedAdmin();
  if (!admin) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

  const db = getDb();
  clearErrorLogs(db);
  return NextResponse.json({ ok: true });
}
