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

// GET /api/ordonnances/[id] - Get a specific ordonnance
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const ordonnance = await db.ordonnance.findUnique({
      where: { id: id },
      include: {
        patient: {
          include: {
            client: true
          }
        },
        fichiers: true
      }
    })

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

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

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

    const {
      patientId,
      numero,
      dateEmission,
      medecin,
      notes
    } = body

    // Check if numero is used by another ordonnance
    if (numero) {
      const existingOrdonnance = await db.ordonnance.findFirst({
        where: {
          numero,
          NOT: {
            id: id
          }
        }
      })

      if (existingOrdonnance) {
        return NextResponse.json(
          { error: 'Une autre ordonnance utilise déjà ce numéro' },
          { status: 400 }
        )
      }
    }

    const ordonnance = await db.ordonnance.update({
      where: { id: id },
      data: {
        patientId: patientId || undefined,
        numero: numero || undefined,
        dateEmission: dateEmission ? new Date(dateEmission) : undefined,
        medecin: medecin !== undefined ? medecin : undefined,
        notes: notes !== undefined ? notes : undefined
      },
      include: {
        patient: {
          include: {
            client: true
          }
        }
      }
    })

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

// DELETE /api/ordonnances/[id] - Delete an ordonnance
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    await db.ordonnance.delete({
      where: { id: id }
    })

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