import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

// GET /api/clients/[id]/patients - Get all patients for a client
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    console.log('API: GET /api/clients/[id]/patients')
    console.log('API: params.id =', id)
    console.log('API: typeof params.id =', typeof id)

    const patients = await db.patient.findMany({
      where: { clientId: id },
      include: {
        ordonnances: {
          include: {
            fichiers: true
          }
        }
      },
      orderBy: {
        dateCreation: 'desc'
      }
    })

    console.log('API: Patients trouvés =', patients.length)
    patients.forEach((p, i) => {
      console.log(`API: Patient ${i}: id=${p.id}, clientId=${p.clientId}`)
    })

    return NextResponse.json(patients)
  } catch (error) {
    console.error('Error fetching patients:', error)
    return NextResponse.json(
      { error: 'Failed to fetch patients' },
      { status: 500 }
    )
  }
}
