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

// GET all purchase invoices
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const statut = searchParams.get('statut')

    const invoices = await db.factureAchat.findMany({
      where: statut ? { statut: statut as any } : undefined,
      include: {
        fournisseur: true,
        lignes: {
          include: {
            produit: true
          }
        },
        fichiers: true
      },
      orderBy: {
        date: 'desc'
      }
    })

    return NextResponse.json(invoices)
  } catch (error) {
    console.error('Error fetching purchase invoices:', error)
    return NextResponse.json(
      { error: 'Impossible de récupérer les factures d\'achat' },
      { status: 500 }
    )
  }
}

// POST create new purchase invoice
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const {
      fournisseurId,
      date,
      lignes,
      montantHT,
      montantTVA,
      montantTTC,
      notes
    } = body

    // Validation
    if (!fournisseurId) {
      return NextResponse.json(
        { error: 'Le fournisseur est requis' },
        { status: 400 }
      )
    }

    if (!lignes || lignes.length === 0) {
      return NextResponse.json(
        { error: 'Au moins une ligne est requise' },
        { status: 400 }
      )
    }

    // Generate invoice number
    const now = new Date(date)
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    
    // Count invoices for this month
    const monthInvoices = await db.factureAchat.count({
      where: {
        date: {
          gte: new Date(year, now.getMonth(), 1),
          lt: new Date(year, now.getMonth() + 1, 1)
        }
      }
    })

    const numero = `A${year}${month}${String(monthInvoices + 1).padStart(4, '0')}`

    // Create invoice with lines in a transaction
    const invoice = await db.factureAchat.create({
      data: {
        fournisseurId,
        numero,
        date: new Date(date),
        statut: 'BROUILLON',
        montantHT: Number(montantHT),
        montantTVA: Number(montantTVA),
        montantTTC: Number(montantTTC),
        notes: notes || null,
        lignes: {
          create: lignes.map((ligne: any) => ({
            produitId: ligne.produitId,
            quantite: ligne.quantite,
            prixUnitaireHT: ligne.prixUnitaireHT,
            tauxTVA: ligne.tauxTVA,
            montantHT: ligne.montantHT,
            montantTVA: ligne.montantTVA,
            montantTTC: ligne.montantTTC
          }))
        }
      },
      include: {
        fournisseur: true,
        lignes: {
          include: {
            produit: true
          }
        }
      }
    })

    return NextResponse.json(invoice, { status: 201 })
  } catch (error) {
    console.error('Error creating purchase invoice:', error)
    return NextResponse.json(
      { error: 'Impossible de créer la facture d\'achat' },
      { status: 500 }
    )
  }
}
