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

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

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

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

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

    // Validate required fields
    if (!patientId || !numero || !dateEmission) {
      return NextResponse.json(
        { error: 'Missing required fields: patientId, numero, dateEmission' },
        { status: 400 }
      )
    }

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

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

    // Check if numero already exists
    const existingOrdonnance = await db.ordonnance.findUnique({
      where: { numero }
    })

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

    const ordonnance = await db.ordonnance.create({
      data: {
        patientId,
        numero,
        dateEmission: new Date(dateEmission),
        medecin: medecin || null,
        notes: notes || null
      },
      include: {
        patient: {
          include: {
            client: true
          }
        }
      }
    })

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