// 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'];

// Royal Mail standard services - these are approximate rates, will be updated via API
// when Royal Mail credentials are available
const DOMESTIC_RATES = {
  // Special Delivery Guaranteed by 9am next working day
  special_next_day: { basePrice: 895, perKg: 0 }, // £8.95 flat
  // Special Delivery Guaranteed by 9am Saturday
  special_saturday: { basePrice: 895, perKg: 0 }, // £8.95 flat
  // Royal Mail 24® - Next working day
  royal_24: { basePrice: 495, perKg: 0 }, // £4.95 flat
  // Royal Mail 48® - 2-3 working days
  royal_48: { basePrice: 295, perKg: 0 }, // £2.95 flat
};

const INTERNATIONAL_RATES = {
  // International Signed
  international_signed: { basePrice: 1495, perKg: 300 }, // £14.95 + £3.00 per kg
  // International Economy
  international_economy: { basePrice: 1095, perKg: 200 }, // £10.95 + £2.00 per kg
};

/**
 * 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());

  // TODO: Replace with actual Royal Mail API call when credentials are available
  // const apiKey = process.env.ROYAL_MAIL_API_KEY;
  // if (apiKey) {
  //   return await fetchRealRoyalMailRates(weightKg, destinationCountry, apiKey);
  // }

  // Fallback to estimated rates
  return calculateEstimatedRates(weightKg, isInternational, destinationCountry);
}

function calculateEstimatedRates(
  weightKg: number,
  isInternational: boolean,
  destinationCountry: string
): ShippingQuote[] {
  const quotes: ShippingQuote[] = [];

  if (isInternational) {
    // International options
    quotes.push({
      service: 'International Signed',
      price: Math.ceil(
        INTERNATIONAL_RATES.international_signed.basePrice +
          INTERNATIONAL_RATES.international_signed.perKg * Math.ceil(weightKg)
      ),
      estimatedDays: 14,
      isInternational: true,
      warning: 'International delivery typically takes 10-14 working days to most destinations',
    });

    quotes.push({
      service: 'International Economy',
      price: Math.ceil(
        INTERNATIONAL_RATES.international_economy.basePrice +
          INTERNATIONAL_RATES.international_economy.perKg * Math.ceil(weightKg)
      ),
      estimatedDays: 21,
      isInternational: true,
      warning: 'Economy international delivery can take 2-3 weeks',
    });
  } else {
    // UK domestic options
    quotes.push({
      service: 'Special Delivery Guaranteed by 9am',
      price: DOMESTIC_RATES.special_next_day.basePrice,
      estimatedDays: 1,
      isInternational: false,
    });

    quotes.push({
      service: 'Royal Mail 24®',
      price: DOMESTIC_RATES.royal_24.basePrice,
      estimatedDays: 1,
      isInternational: false,
    });

    quotes.push({
      service: 'Royal Mail 48®',
      price: DOMESTIC_RATES.royal_48.basePrice,
      estimatedDays: 3,
      isInternational: false,
    });
  }

  return quotes;
}

/**
 * TODO: Implement actual Royal Mail API integration
 * This would call Royal Mail's postage API with real-time rates
 * Requires Royal Mail credentials and API access
 */
// async function fetchRealRoyalMailRates(
//   weightKg: number,
//   destinationCountry: string,
//   apiKey: string
// ): Promise<ShippingQuote[]> {
//   const endpoint = 'https://api.royalmail.com/shipping/rates';
//   // Implementation would call Royal Mail API
// }

/**
 * 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' : ''}`;
}
