import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import * as platformClient from '@/lib/platform-client';
export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    const url = new URL(req.url);
    const category = url.searchParams.get('category') ?? undefined;
    const limit = parseInt(url.searchParams.get('limit') ?? '100', 10);
    const offset = parseInt(url.searchParams.get('offset') ?? '0', 10);
    const summary = url.searchParams.get('summary') === 'true';
    if (summary) {
      const { stats } = await platformClient.getAuditStats(90);
      const total = Object.values(stats).reduce((s, n) => s + n, 0);
      const failedLogins = stats['login_failed'] ?? 0;
      return NextResponse.json({ total, failedLogins });
    }
    const { records, count } = await platformClient.queryAudit({ category, limit, offset });
    return NextResponse.json({ entries: records, total: count });
  } catch (error) {
    logError('Audit error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
