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

// GET single purchase invoice
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const invoice = await db.factureAchat.findUnique({
      where: { id: id },
      include: {
        fournisseur: true,
        lignes: {
          include: {
            produit: true
          }
        },
        fichiers: true
      }
    })

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

    return NextResponse.json(invoice)
  } catch (error) {
    console.error('Error fetching purchase invoice:', error)
    return NextResponse.json(
      { error: 'Impossible de récupérer la facture' },
      { status: 500 }
    )
  }
}

// DELETE purchase invoice (only if BROUILLON)
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Check if invoice exists and is in BROUILLON status
    const invoice = await db.factureAchat.findUnique({
      where: { id: id }
    })

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

    if (invoice.statut !== 'BROUILLON') {
      return NextResponse.json(
        { error: 'Seules les factures en brouillon peuvent être supprimées' },
        { status: 400 }
      )
    }

    // Delete invoice (lines will be cascade deleted)
    await db.factureAchat.delete({
      where: { id: id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting purchase invoice:', error)
    return NextResponse.json(
      { error: 'Impossible de supprimer la facture' },
      { status: 500 }
    )
  }
}
