import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getRoyalMailShippingQuotes, formatShippingPrice } from '@/lib/royalmail-shipping';

interface CartItem {
  productId: string;
  quantity: number;
}

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

    if (!items || !Array.isArray(items) || !country) {
      return NextResponse.json(
        { error: 'Missing items or country' },
        { status: 400 }
      );
    }

    // Calculate total weight from cart items
    let totalWeightGrams = 0;

    for (const item of items) {
      const product = await prisma.product.findUnique({
        where: { id: item.productId },
        select: { weightGrams: true },
      });

      if (product?.weightGrams) {
        totalWeightGrams += product.weightGrams * item.quantity;
      }
    }

    // If no weight is set for products, return default shipping
    if (totalWeightGrams === 0) {
      totalWeightGrams = 500; // Default 500g if not specified
    }

    // Get Royal Mail shipping quotes
    const quotes = await getRoyalMailShippingQuotes(totalWeightGrams, country);

    return NextResponse.json({
      success: true,
      totalWeightGrams,
      totalWeightKg: (totalWeightGrams / 1000).toFixed(2),
      country,
      quotes: quotes.map((q) => ({
        ...q,
        priceFormatted: formatShippingPrice(q.price),
      })),
    });
  } catch (error) {
    console.error('Error calculating shipping quotes:', error);
    return NextResponse.json(
      { error: 'Failed to calculate shipping' },
      { status: 500 }
    );
  }
}
