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

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

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

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

    const {
      nom,
      prenom,
      email,
      telephone,
      adresse,
      ville,
      codePostal,
      dateNaissance,
      notes
    } = body

    // Validate required fields
    if (!nom || !prenom || !telephone) {
      return NextResponse.json(
        { error: 'Missing required fields: nom, prenom, telephone' },
        { status: 400 }
      )
    }

    // Check if telephone already exists
    const existingClient = await db.client.findUnique({
      where: { telephone }
    })

    if (existingClient) {
      return NextResponse.json(
        { error: 'Un client avec ce numéro de téléphone existe déjà' },
        { status: 400 }
      )
    }

    const client = await db.client.create({
      data: {
        nom,
        prenom,
        email: email || null,
        telephone,
        adresse: adresse || null,
        ville: ville || null,
        codePostal: codePostal || null,
        dateNaissance: dateNaissance ? new Date(dateNaissance) : null,
        notes: notes || null
      }
    })

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