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

export async function GET() {
  try {
    const guias = await prisma.airwayBill.findMany({
      orderBy: [{ deliverDate: 'desc' }, { shipDate: 'desc' }, { createdAt: 'desc' }]
    });
    return NextResponse.json(guias);
  } catch (error: any) {
    return NextResponse.json({ error: error.message || 'Error fetching guías' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { agency, deliverDate, shipDate, awb, master, notes, status } = body;

    if (!agency || !deliverDate || !shipDate || !awb) {
      return NextResponse.json({ error: 'Agencia, Deliver Date, Ship Date y AWB son requeridos' }, { status: 400 });
    }

    // Auto-extract last 4 digits of AWB if master is not provided
    const cleanAwb = awb.trim();
    const digitsOnly = cleanAwb.replace(/\D/g, '');
    const autoMaster = master?.trim() || (digitsOnly.length >= 4 ? digitsOnly.slice(-4) : cleanAwb.slice(-4));

    const guia = await prisma.airwayBill.create({
      data: {
        agency: agency.trim().toUpperCase(),
        deliverDate: parseExcelDate(deliverDate),
        shipDate: parseExcelDate(shipDate),
        awb: cleanAwb,
        master: autoMaster,
        status: status || 'ACTIVE',
        notes: notes || null
      }
    });

    return NextResponse.json(guia);
  } catch (error: any) {
    if (error.code === 'P2002') {
      return NextResponse.json({ error: 'Ya existe una guía con este número de AWB' }, { status: 400 });
    }
    return NextResponse.json({ error: error.message || 'Error creando guía' }, { status: 500 });
  }
}
