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

// GET /api/pos/sales/[id] - Get a specific sale
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const sale = await db.vente.findUnique({
      where: { id: id },
      include: {
        client: true,
        employe: true,
        lignes: {
          include: {
            produit: true
          }
        },
        paiements: true,
        fichiers: true
      }
    })

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

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

// PATCH /api/pos/sales/[id] - Update sale status
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()
    const { statut, notes } = body

    // Validate status
    if (statut && !Object.values(StatutVente).includes(statut)) {
      return NextResponse.json(
        { error: 'Invalid status value' },
        { status: 400 }
      )
    }

    // Check if sale exists
    const existingSale = await db.vente.findUnique({
      where: { id: id }
    })

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

    // Update sale
    const updatedSale = await db.vente.update({
      where: { id: id },
      data: {
        ...(statut && { statut }),
        ...(notes !== undefined && { notes })
      },
      include: {
        client: true,
        lignes: {
          include: {
            produit: true
          }
        },
        paiements: true
      }
    })

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

// DELETE /api/pos/sales/[id] - Cancel/Delete a sale
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Check if sale exists
    const existingSale = await db.vente.findUnique({
      where: { id: id },
      include: {
        lignes: true
      }
    })

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

    // If sale is already paid, we can't delete it, only cancel
    if (existingSale.statut === StatutVente.PAYEE) {
      // Update status to ANNULEE
      const cancelledSale = await db.vente.update({
        where: { id: id },
        data: {
          statut: StatutVente.ANNULEE
        }
      })

      return NextResponse.json(cancelledSale)
    }

    // If sale is not paid, we can delete it and restore stock
    await db.$transaction(async (tx) => {
      // Restore product stock
      for (const ligne of existingSale.lignes) {
        await tx.produit.update({
          where: { id: ligne.produitId },
          data: {
            stock: {
              increment: ligne.quantite
            }
          }
        })
      }

      // Delete sale (cascade will delete lines and payments)
      await tx.vente.delete({
        where: { id: id }
      })
    })

    return NextResponse.json({ message: 'Sale deleted successfully' })
  } catch (error) {
    console.error('Error deleting sale:', error)
    return NextResponse.json(
      { error: 'Failed to delete sale' },
      { status: 500 }
    )
  }
}
