// Royal Mail shipping integration for domestic and international postage

export interface ShippingQuote {
  service: string;
  price: number; // in pence
  estimatedDays: number;
  isInternational: boolean;
  warning?: string;
}

// UK postal areas
const UK_COUNTRIES = ['GB', 'UK'];

// Default fallback rates if no database rates are configured
// These are standard Royal Mail pricing estimates
const DEFAULT_RATES = {
  DOMESTIC: [
    { service: 'Special Delivery Guaranteed by 9am', basePrice: 895, perKg: 0, estimatedDays: 1, isInternational: false },
    { service: 'Royal Mail 24®', basePrice: 495, perKg: 0, estimatedDays: 1, isInternational: false },
    { service: 'Royal Mail 48®', basePrice: 295, perKg: 0, estimatedDays: 3, isInternational: false },
  ],
  INTERNATIONAL: [
    { service: 'International Signed', basePrice: 1495, perKg: 300, estimatedDays: 14, isInternational: true },
    { service: 'International Economy', basePrice: 1095, perKg: 200, estimatedDays: 21, isInternational: true },
  ],
};

/**
 * Calculate Royal Mail postage cost based on weight and destination
 * @param weightGrams Total weight in grams
 * @param destinationCountry ISO 2-letter country code (e.g., 'GB', 'US')
 * @returns Array of available shipping options with prices
 */
export async function getRoyalMailShippingQuotes(
  weightGrams: number,
  destinationCountry: string
): Promise<ShippingQuote[]> {
  const weightKg = weightGrams / 1000;
  const isInternational = !UK_COUNTRIES.includes(destinationCountry.toUpperCase());

  try {
    // Try to fetch rates from database first
    const { prisma } = await import('@/lib/prisma');
    const dbRates = await prisma.shippingRate.findMany({
      where: {
        active: true,
        isInternational,
      },
    });

    if (dbRates.length > 0) {
      console.log('📦 Using shipping rates from database');
      return dbRates.map((rate) => ({
        service: rate.service,
        price: Math.ceil(rate.basePrice + rate.pricePerKg * Math.ceil(weightKg)),
        estimatedDays: rate.estimatedDays,
        isInternational: rate.isInternational,
      }));
    }
  } catch (error) {
    console.warn('Could not fetch database rates, using defaults:', error);
  }

  // Fallback to default rates
  console.log('📦 Using default Royal Mail rates');
  return calculateEstimatedRates(weightKg, isInternational, destinationCountry);
}

function calculateEstimatedRates(
  weightKg: number,
  isInternational: boolean,
  destinationCountry: string
): ShippingQuote[] {
  const rates = isInternational ? DEFAULT_RATES.INTERNATIONAL : DEFAULT_RATES.DOMESTIC;

  return rates.map((rate) => ({
    service: rate.service,
    price: Math.ceil(rate.basePrice + rate.perKg * Math.ceil(weightKg)),
    estimatedDays: rate.estimatedDays,
    isInternational: rate.isInternational,
  }));
}


/**
 * Format price from pence to pounds string
 */
export function formatShippingPrice(pence: number): string {
  return `£${(pence / 100).toFixed(2)}`;
}

/**
 * Get delivery estimate text with international warning if needed
 */
export function getDeliveryEstimate(quote: ShippingQuote): string {
  if (quote.warning) {
    return quote.warning;
  }
  return `Estimated delivery: ${quote.estimatedDays} working day${quote.estimatedDays > 1 ? 's' : ''}`;
}
