import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireAdmin } from '@/lib/auth';
import { Lead } from '@/lib/types';

export async function GET(request: NextRequest) {
  const unauthorized = await requireAdmin();
  if (unauthorized) return unauthorized;

  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get('page') || '1');
  const limit = parseInt(searchParams.get('limit') || '50');
  const offset = (page - 1) * limit;

  const leads = await query<Lead>(
    'SELECT * FROM leads ORDER BY created_at DESC LIMIT $1 OFFSET $2',
    [limit, offset]
  );

  const [{ count }] = await query<{ count: string }>(
    'SELECT COUNT(*) as count FROM leads'
  );

  return NextResponse.json({
    leads,
    total: parseInt(count),
    page,
    pages: Math.ceil(parseInt(count) / limit),
  });
}
