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

// POST /api/atelier/orders/[id] - Update workshop status
// Note: Using POST instead of PATCH because the gateway blocks PATCH requests
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()
    const { statutAtelier } = body

    console.log('API: POST /api/atelier/orders/[id]')
    console.log('API: orderId =', id)
    console.log('API: statutAtelier =', statutAtelier)
    console.log('API: Valid StatutAtelier values:', Object.values(StatutAtelier))

    // Validate status
    if (!statutAtelier || !Object.values(StatutAtelier).includes(statutAtelier)) {
      console.log('API: Invalid status - returning 400')
      return NextResponse.json(
        { error: 'Invalid workshop status' },
        { status: 400 }
      )
    }

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

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

    // Update order status
    const updateData: any = {
      statutAtelier: statutAtelier as StatutAtelier,
      dateAtelier: new Date()
    }

    // Add dateRetrait if status is RETIRE
    if (statutAtelier === 'RETIRE') {
      updateData.dateRetrait = new Date()
    }

    const updatedOrder = await db.vente.update({
      where: { id: id },
      data: updateData,
      include: {
        client: true,
        lignes: {
          include: {
            produit: true
          },
          where: {
            produit: {
              categorie: {
                in: ['MONTURE', 'VERRE']
              }
            }
          }
        },
        paiements: true
      }
    })

    console.log('API: Order updated successfully, new status:', updatedOrder.statutAtelier)

    // Fetch patients for the client
    let patients = []
    if (updatedOrder.clientId) {
      patients = await db.patient.findMany({
        where: {
          clientId: updatedOrder.clientId
        },
        orderBy: {
          dateCreation: 'desc'
        },
        take: 2
      })
    }

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

// GET /api/atelier/orders/[id] - Get specific work order details
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const order = await db.vente.findUnique({
      where: { id: id },
      include: {
        client: true,
        lignes: {
          include: {
            produit: true
          }
        },
        paiements: true
      }
    })

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

    // Fetch patients for the client
    let patients = []
    if (order.clientId) {
      patients = await db.patient.findMany({
        where: {
          clientId: order.clientId
        },
        orderBy: {
          dateCreation: 'desc'
        },
        take: 2
      })
    }

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