import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function POST(req: Request) {
  try {
    const { data } = await req.json();

    if (!Array.isArray(data) || data.length === 0) {
      return NextResponse.json({ error: 'No data provided' }, { status: 400 });
    }

    let updatedLines = 0;
    let notFoundLines = 0;

    for (const row of data) {
      const trackingNumber = row.TRACKING?.toString() || row.Tracking?.toString();
      const po = row.Ponumber?.toString();
      const orderNumber = row.CUSTnbr?.toString();
      const productCode = row.Item?.toString();

      if (!trackingNumber || !po || !orderNumber || !productCode) {
        continue;
      }

      // Find an order line that matches the PO, Order Number, Product Code and doesn't have a tracking number yet
      const lines = await prisma.orderLine.findMany({
        where: {
          order: {
            po: po,
            orderNumber: orderNumber
          },
          product: {
            code: productCode
          },
          trackingNumber: null
        },
        take: 1
      });

      if (lines.length > 0) {
        const line = lines[0];
        await prisma.orderLine.update({
          where: { id: line.id },
          data: { 
            trackingNumber,
            status: 'SHIPPED'
          }
        });
        
        // Let's also check if all lines of the order are SHIPPED, to update the Order status
        const otherPendingLines = await prisma.orderLine.count({
          where: {
            orderId: line.orderId,
            status: { not: 'SHIPPED' },
            id: { not: line.id } // exclude the one we just updated
          }
        });

        if (otherPendingLines === 0) {
          await prisma.order.update({
            where: { id: line.orderId },
            data: { status: 'SHIPPED' }
          });
        }
        
        updatedLines++;
      } else {
        notFoundLines++;
      }
    }

    return NextResponse.json({ message: 'Success', updatedLines, notFoundLines });

  } catch (error: any) {
    console.error("Error importing tracking:", error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
