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

// GET /api/pos/clients - Get all clients
export async function GET(request: NextRequest) {
  try {
    const clients = await db.client.findMany({
      orderBy: {
        nom: 'asc'
      }
    })

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

// POST /api/pos/clients - Create a new client
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { nom, prenom, email, telephone } = 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 }
      )
    }

    // Create client
    const client = await db.client.create({
      data: {
        nom,
        prenom,
        email: email || null,
        telephone
      }
    })

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