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

// POST validate invoice and update stock
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Get invoice with lines
    const invoice = await db.factureAchat.findUnique({
      where: { id: id },
      include: {
        lignes: true
      }
    })

    if (!invoice) {
      return NextResponse.json(
        { error: 'Facture non trouvée' },
        { status: 404 }
      )
    }

    if (invoice.statut !== 'BROUILLON') {
      return NextResponse.json(
        { error: 'Cette facture a déjà été validée' },
        { status: 400 }
      )
    }

    // Update stock for each line
    for (const ligne of invoice.lignes) {
      await db.produit.update({
        where: { id: ligne.produitId },
        data: {
          stock: {
            increment: ligne.quantite
          }
        }
      })
    }

    // Update invoice status and set reception date
    const updatedInvoice = await db.factureAchat.update({
      where: { id: id },
      data: {
        statut: 'VALIDE',
        dateReception: new Date()
      },
      include: {
        fournisseur: true,
        lignes: {
          include: {
            produit: true
          }
        }
      }
    })

    return NextResponse.json(updatedInvoice)
  } catch (error) {
    console.error('Error validating purchase invoice:', error)
    return NextResponse.json(
      { error: 'Impossible de valider la facture' },
      { status: 500 }
    )
  }
}
