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

// GET /api/fournisseurs/[id] - Get a single supplier
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const supplier = await db.fournisseur.findUnique({
      where: { id: id },
      include: {
        _count: {
          select: {
            produits: true,
            facturesAchat: true,
          },
        },
      },
    })

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

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

// PUT /api/fournisseurs/[id] - Update a supplier
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()

    // Check if supplier exists
    const existingSupplier = await db.fournisseur.findUnique({
      where: { id: id },
    })

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

    // Validate required fields
    if (!body.nom) {
      return NextResponse.json(
        { error: 'Missing required field: nom' },
        { status: 400 }
      )
    }

    const supplier = await db.fournisseur.update({
      where: { id: id },
      data: {
        nom: body.nom,
        contact: body.contact !== undefined ? body.contact : existingSupplier.contact,
        email: body.email !== undefined ? body.email : existingSupplier.email,
        telephone: body.telephone !== undefined ? body.telephone : existingSupplier.telephone,
        adresse: body.adresse !== undefined ? body.adresse : existingSupplier.adresse,
        ville: body.ville !== undefined ? body.ville : existingSupplier.ville,
        codePostal: body.codePostal !== undefined ? body.codePostal : existingSupplier.codePostal,
        notes: body.notes !== undefined ? body.notes : existingSupplier.notes,
        actif: body.actif !== undefined ? body.actif : existingSupplier.actif,
      },
    })

    return NextResponse.json(supplier)
  } catch (error) {
    console.error('Error updating supplier:', error)
    return NextResponse.json(
      { error: 'Failed to update supplier' },
      { status: 500 }
    )
  }
}

// DELETE /api/fournisseurs/[id] - Delete a supplier
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Check if supplier exists
    const existingSupplier = await db.fournisseur.findUnique({
      where: { id: id },
      include: {
        _count: {
          select: {
            produits: true,
            facturesAchat: true,
          },
        },
      },
    })

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

    // Check if supplier has associated products or invoices
    if (existingSupplier._count.produits > 0) {
      return NextResponse.json(
        { error: 'Cannot delete supplier with associated products. Please remove or reassign products first.' },
        { status: 400 }
      )
    }

    if (existingSupplier._count.facturesAchat > 0) {
      return NextResponse.json(
        { error: 'Cannot delete supplier with associated purchase invoices. Please archive the supplier instead.' },
        { status: 400 }
      )
    }

    // Delete the supplier
    await db.fournisseur.delete({
      where: { id: id },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting supplier:', error)
    return NextResponse.json(
      { error: 'Failed to delete supplier' },
      { status: 500 }
    )
  }
}
