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

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

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

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

// PUT /api/clients/[id] - Update a client
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    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 is used by another client
    const existingClient = await db.client.findFirst({
      where: {
        telephone,
        NOT: {
          id: id
        }
      }
    })

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

    const client = await db.client.update({
      where: { id: id },
      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)
  } catch (error) {
    console.error('Error updating client:', error)
    return NextResponse.json(
      { error: 'Failed to update client' },
      { status: 500 }
    )
  }
}

// DELETE /api/clients/[id] - Delete a client
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Check if client has sales
    const salesCount = await db.vente.count({
      where: { clientId: id }
    })

    if (salesCount > 0) {
      return NextResponse.json(
        { error: 'Impossible de supprimer un client qui a des ventes associées' },
        { status: 400 }
      )
    }

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

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