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

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { mappings } = body as { mappings: { po: string; tracking: string }[] };

    if (!mappings || !Array.isArray(mappings)) {
      return NextResponse.json({ error: 'Formato inválido' }, { status: 400 });
    }

    let updatedCount = 0;
    const notFound: string[] = [];

    for (const mapping of mappings) {
      // Use findFirst since 'po' alone is not a unique field (compound unique with orderNumber)
      const order = await prisma.order.findFirst({
        where: { po: mapping.po },
        include: { lines: true }
      });

      if (!order) {
        notFound.push(mapping.po);
        continue;
      }

      // Update all lines of that order with the tracking number
      const res = await prisma.orderLine.updateMany({
        where: { orderId: order.id },
        data: { trackingNumber: mapping.tracking }
      });

      if (res.count > 0) {
        updatedCount += res.count;
      } else {
        notFound.push(mapping.po);
      }
    }

    return NextResponse.json({ updated: updatedCount, notFound });

  } catch (error: unknown) {
    const msg = error instanceof Error ? error.message : 'Error procesando trackings';
    console.error('Error masstracking:', error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
