import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { fetchRoyalMailTracking, mapTrackingStatusToOrderStatus } from '@/lib/royalmail';

export async function POST(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const order = await prisma.order.findUnique({
      where: { id: params.id },
    });

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

    if (!order.trackingNumber) {
      return NextResponse.json({ error: 'No tracking number set for this order' }, { status: 400 });
    }

    // Fetch tracking data from Royal Mail
    const trackingData = await fetchRoyalMailTracking(order.trackingNumber);

    if (!trackingData) {
      return NextResponse.json({ error: 'Could not fetch tracking data from Royal Mail' }, { status: 400 });
    }

    // Map Royal Mail status to our order status
    const newStatus = mapTrackingStatusToOrderStatus(trackingData.status);

    // Update order with new status
    const updated = await prisma.order.update({
      where: { id: params.id },
      data: {
        status: newStatus,
      },
    });

    console.log(`✓ Order ${params.id} tracking synced: ${trackingData.status} → ${newStatus}`);

    return NextResponse.json({
      success: true,
      trackingData,
      orderStatus: newStatus,
    });
  } catch (err) {
    console.error('Error syncing tracking:', err);
    return NextResponse.json(
      { error: 'Failed to sync tracking data' },
      { status: 500 }
    );
  }
}
