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

export async function POST(request: Request) {
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    
    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 });
    }

    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);
    
    const wb = xlsx.read(buffer, { type: 'buffer' });
    const wsname = wb.SheetNames[0];
    const ws = wb.Sheets[wsname];
    
    const data = xlsx.utils.sheet_to_json(ws);
    
    let createdCount = 0;
    
    for (const row of data as any[]) {
      const code = row['Código']?.toString();
      const name = row['Nombre del Producto']?.toString();
      const tariffCode = row['Tarifa Arancelaria']?.toString() || null;
      const declaredValueStr = row['Valor Declarado']?.toString();
      const declaredValue = declaredValueStr ? parseFloat(declaredValueStr) : null;
      
      if (code && name) {
        // Upsert to handle updates or new products
        await prisma.product.upsert({
          where: { code },
          update: { name, tariffCode, declaredValue },
          create: { code, name, tariffCode, declaredValue }
        });
        createdCount++;
      }
    }

    return NextResponse.json({ success: true, count: createdCount });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Error processing excel file' }, { status: 500 });
  }
}
