// Royal Mail Parcel Tracking API integration
// Uses Royal Mail's public tracking API to get shipment status

export type RoyalMailTrackingStatus =
  | 'Pending'
  | 'Collected'
  | 'In Transit'
  | 'Out for Delivery'
  | 'Delivered'
  | 'Undeliverable'
  | 'Unknown';

export interface RoyalMailTrackingEvent {
  status: RoyalMailTrackingStatus;
  timestamp: Date;
  location?: string;
  detail?: string;
}

export interface RoyalMailTrackingData {
  trackingNumber: string;
  status: RoyalMailTrackingStatus;
  events: RoyalMailTrackingEvent[];
  lastUpdate: Date;
}

/**
 * Fetch tracking data from Royal Mail API
 * Uses the public Royal Mail tracking service (no authentication required for basic tracking)
 */
export async function fetchRoyalMailTracking(trackingNumber: string): Promise<RoyalMailTrackingData | null> {
  try {
    // Royal Mail tracking API endpoint
    const url = `https://www3.royalmail.com/api/v1/track-and-trace?mailPieces=${trackingNumber}`;

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
      },
    });

    if (!response.ok) {
      console.error('Royal Mail API error:', response.status, response.statusText);
      return null;
    }

    const data = await response.json();

    // Parse Royal Mail's response format
    if (!data.mailPieces || !Array.isArray(data.mailPieces) || data.mailPieces.length === 0) {
      console.warn('No tracking data found for:', trackingNumber);
      return null;
    }

    const mailPiece = data.mailPieces[0];

    // Extract status and events
    const status: RoyalMailTrackingStatus = parseRoyalMailStatus(mailPiece.status);
    const events: RoyalMailTrackingEvent[] = (mailPiece.events || []).map((event: any) => ({
      status: parseRoyalMailStatus(event.status),
      timestamp: new Date(event.datetime),
      location: event.location || event.name,
      detail: event.detail,
    }));

    return {
      trackingNumber: mailPiece.mailPieceId,
      status,
      events: events.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime()),
      lastUpdate: new Date(),
    };
  } catch (error) {
    console.error('Error fetching Royal Mail tracking:', error);
    return null;
  }
}

/**
 * Map Royal Mail status strings to our internal status format
 */
function parseRoyalMailStatus(royalMailStatus: string): RoyalMailTrackingStatus {
  const status = String(royalMailStatus).toLowerCase();

  if (status.includes('delivered')) return 'Delivered';
  if (status.includes('out for delivery')) return 'Out for Delivery';
  if (status.includes('in transit')) return 'In Transit';
  if (status.includes('collected')) return 'Collected';
  if (status.includes('pending')) return 'Pending';
  if (status.includes('undeliverable')) return 'Undeliverable';

  return 'Unknown';
}

/**
 * Convert Royal Mail tracking status to our order status
 */
export function mapTrackingStatusToOrderStatus(trackingStatus: RoyalMailTrackingStatus): string {
  switch (trackingStatus) {
    case 'Delivered':
      return 'DELIVERED';
    case 'Out for Delivery':
      return 'SHIPPED';
    case 'In Transit':
      return 'SHIPPED';
    case 'Collected':
      return 'PRINTED';
    case 'Pending':
      return 'PRINTED';
    case 'Undeliverable':
      return 'SHIPPED'; // Keep as shipped, admin needs to handle
    default:
      return 'SHIPPED';
  }
}
