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

// GET /api/fournisseurs/[id]/factures - Get all purchase invoices for a supplier
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Check if supplier exists
    const supplier = await db.fournisseur.findUnique({
      where: { id: id },
    })

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

    // Get all invoices for this supplier
    const factures = await db.factureAchat.findMany({
      where: {
        fournisseurId: id,
      },
      orderBy: {
        date: 'desc',
      },
    })

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