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

// GET /api/atelier/orders - Get all work orders (sales that need mounting)
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams
    const status = searchParams.get('status') as StatutAtelier | null

    // Build where clause
    const where: any = {
      statut: 'PAYEE', // Only paid sales go to workshop
      lignes: {
        some: {
          produit: {
            categorie: {
              in: ['MONTURE', 'VERRE'] // Only sales with frames or lenses
            }
          }
        }
      }
    }

    // Filter by status if provided
    if (status && status !== 'ALL') {
      where.statutAtelier = status
    }

    const workOrders = await db.vente.findMany({
      where,
      include: {
        client: true,
        lignes: {
          include: {
            produit: true
          },
          where: {
            produit: {
              categorie: {
                in: ['MONTURE', 'VERRE']
              }
            }
          }
        },
        paiements: true
      },
      orderBy: [
        { statutAtelier: 'asc' }, // EN_ATTENTE first, then EN_COURS, etc.
        { date: 'desc' }
      ]
    })

    // Fetch patients for each client to get vision measurements
    const workOrdersWithPatients = await Promise.all(
      workOrders.map(async (order) => {
        if (!order.clientId) {
          return { ...order, patients: [] }
        }

        const patients = await db.patient.findMany({
          where: {
            clientId: order.clientId
          },
          orderBy: {
            dateCreation: 'desc'
          },
          take: 2 // Get the 2 most recent vision measurements
        })

        return {
          ...order,
          patients
        }
      })
    )

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