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

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

    const patient = await db.patient.findUnique({
      where: { id },
      include: {
        client: true,
        ordonnances: {
          include: {
            fichiers: true
          }
        }
      }
    })

    if (!patient) {
      return NextResponse.json(
        { error: 'Patient not found' },
        { status: 404 }
      )
    }

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

// PUT /api/patients/[id] - Update a patient
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()

    const {
      clientId,
      odSphere,
      odCylindre,
      odAxe,
      ogSphere,
      ogCylindre,
      ogAxe,
      addition,
      pd,
      hauteur,
      notes
    } = body

    const patient = await db.patient.update({
      where: { id },
      data: {
        clientId: clientId || undefined,
        odSphere: odSphere !== undefined ? parseFloat(odSphere) : undefined,
        odCylindre: odCylindre !== undefined ? parseFloat(odCylindre) : undefined,
        odAxe: odAxe !== undefined ? parseInt(odAxe) : undefined,
        ogSphere: ogSphere !== undefined ? parseFloat(ogSphere) : undefined,
        ogCylindre: ogCylindre !== undefined ? parseFloat(ogCylindre) : undefined,
        ogAxe: ogAxe !== undefined ? parseInt(ogAxe) : undefined,
        addition: addition !== undefined ? parseFloat(addition) : undefined,
        pd: pd !== undefined ? parseFloat(pd) : undefined,
        hauteur: hauteur !== undefined ? parseFloat(hauteur) : undefined,
        notes: notes !== undefined ? notes : undefined
      },
      include: {
        client: true,
        ordonnances: true
      }
    })

    return NextResponse.json(patient)
  } catch (error) {
    console.error('Error updating patient:', error)
    return NextResponse.json(
      { error: 'Failed to update patient' },
      { status: 500 }
    )
  }
}

// DELETE /api/patients/[id] - Delete a patient
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    await db.patient.delete({
      where: { id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting patient:', error)
    return NextResponse.json(
      { error: 'Failed to delete patient' },
      { status: 500 }
    )
  }
}
