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

// GET /api/patients - Get all patients
export async function GET() {
  try {
    const patients = await db.patient.findMany({
      include: {
        client: true,
        ordonnances: true
      },
      orderBy: {
        dateCreation: 'desc'
      }
    })

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

// POST /api/patients - Create a new patient
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

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

    // Validate required field
    if (!clientId) {
      return NextResponse.json(
        { error: 'Missing required field: clientId' },
        { status: 400 }
      )
    }

    // Check if client exists
    const client = await db.client.findUnique({
      where: { id: clientId }
    })

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

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

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