export const dynamic = 'force-dynamic';
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(request: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { searchParams } = new URL(request.url);
    const status = searchParams?.get('status');
    const page = parseInt(searchParams?.get('page') ?? '1');
    const perPage = 20;

    const where: any = {};
    if (status && status !== 'ALL') where.status = status;

    const [leads, total] = await Promise.all([
      prisma.lead.findMany({
        where,
        include: { vehicle: { select: { title: true, id: true } } },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * perPage,
        take: perPage,
      }),
      prisma.lead.count({ where }),
    ]);

    return NextResponse.json({ leads: leads ?? [], total: total ?? 0 });
  } catch (error: any) {
    return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 });
  }
}
