/**
 * Carrier tracking URL resolver.
 *
 * Priority:
 *  1. Exact carrier name match (case-insensitive, partial)
 *  2. Tracking number pattern detection
 *  3. Google search fallback so the user always gets something useful
 */

export interface CarrierInfo {
  name: string;
  trackingUrl: string;
  /** Short identifier used for display */
  code: string;
}

/** Map carrier name keywords → tracking URL builder */
const CARRIER_NAME_MAP: Array<{
  keywords: string[];
  code: string;
  buildUrl: (num: string) => string;
}> = [
  {
    keywords: ["delhivery"],
    code: "Delhivery",
    buildUrl: (n) => `https://www.delhivery.com/tracking/?tracking_id=${n}`,
  },
  {
    keywords: ["bluedart", "blue dart"],
    code: "Blue Dart",
    buildUrl: (n) => `https://www.bluedart.com/tracking/${n}`,
  },
  {
    keywords: ["dtdc"],
    code: "DTDC",
    buildUrl: (n) =>
      `https://tracking.dtdc.com/ctbs-tracking/customerInterface.tr?submitName=showCustInterface&cnNo=${n}`,
  },
  {
    keywords: ["fedex", "fed ex"],
    code: "FedEx",
    buildUrl: (n) =>
      `https://www.fedex.com/apps/fedextrack/?tracknumbers=${n}`,
  },
  {
    keywords: ["dhl"],
    code: "DHL",
    buildUrl: (n) =>
      `https://www.dhl.com/en/express/tracking.html?AWB=${n}&brand=DHL`,
  },
  {
    keywords: ["ups"],
    code: "UPS",
    buildUrl: (n) => `https://www.ups.com/track?tracknum=${n}`,
  },
  {
    keywords: ["usps"],
    code: "USPS",
    buildUrl: (n) =>
      `https://tools.usps.com/go/TrackConfirmAction?tLabels=${n}`,
  },
  {
    keywords: ["india post", "indiapost", "speed post", "speedpost"],
    code: "India Post",
    buildUrl: (n) =>
      `https://www.indiapost.gov.in/_layouts/15/dop.portal.tracking/TrackConsignment.aspx?q=${n}`,
  },
  {
    keywords: ["ekart"],
    code: "Ekart",
    buildUrl: (n) => `https://ekartlogistics.com/shipmenttrack/${n}`,
  },
  {
    keywords: ["xpressbees"],
    code: "XpressBees",
    buildUrl: (n) => `https://www.xpressbees.com/shipment/tracking/?awb=${n}`,
  },
  {
    keywords: ["ecom express", "ecomexpress"],
    code: "Ecom Express",
    buildUrl: (n) => `https://ecomexpress.in/tracking/?awb_field=${n}`,
  },
  {
    keywords: ["amazon logistics", "amazon"],
    code: "Amazon",
    buildUrl: (n) => `https://track.amazon.in/tracking/${n}`,
  },
  {
    keywords: ["shiprocket"],
    code: "Shiprocket",
    buildUrl: (n) => `https://shiprocket.co/tracking/${n}`,
  },
  {
    keywords: ["shadowfax"],
    code: "Shadowfax",
    buildUrl: (n) => `https://tracker.shadowfax.in/?waybill=${n}`,
  },
  {
    keywords: ["gati"],
    code: "Gati",
    buildUrl: (n) => `https://www.gati.com/tracking/?awb=${n}`,
  },
  {
    keywords: ["maruti", "maruti courier"],
    code: "Maruti Courier",
    buildUrl: (n) =>
      `https://www.maruticourier.com/track-shipment/?trackno=${n}`,
  },
  {
    keywords: ["dotzot"],
    code: "DotZot",
    buildUrl: (n) => `https://www.dotzot.in/tracking/?awbno=${n}`,
  },
];

/** Tracking number regex patterns → carrier resolver */
const PATTERN_MAP: Array<{
  pattern: RegExp;
  code: string;
  buildUrl: (num: string) => string;
}> = [
  // UPS: starts with 1Z
  {
    pattern: /^1Z[A-Z0-9]{16}$/,
    code: "UPS",
    buildUrl: (n) => `https://www.ups.com/track?tracknum=${n}`,
  },
  // FedEx: 12 or 15-digit numeric
  {
    pattern: /^\d{12}$|^\d{15}$/,
    code: "FedEx",
    buildUrl: (n) =>
      `https://www.fedex.com/apps/fedextrack/?tracknumbers=${n}`,
  },
  // USPS: starts with 94/93/92/91/82 + 20 digits
  {
    pattern: /^(94|93|92|91|82)\d{20}$/,
    code: "USPS",
    buildUrl: (n) =>
      `https://tools.usps.com/go/TrackConfirmAction?tLabels=${n}`,
  },
  // India Post: 2 letters + 9 digits + "IN"
  {
    pattern: /^[A-Z]{2}\d{9}IN$/,
    code: "India Post",
    buildUrl: (n) =>
      `https://www.indiapost.gov.in/_layouts/15/dop.portal.tracking/TrackConsignment.aspx?q=${n}`,
  },
  // Ekart: starts with FMPP
  {
    pattern: /^FMPP/,
    code: "Ekart",
    buildUrl: (n) => `https://ekartlogistics.com/shipmenttrack/${n}`,
  },
  // DHL: starts with JD + digits
  {
    pattern: /^JD\d+$/,
    code: "DHL",
    buildUrl: (n) =>
      `https://www.dhl.com/en/express/tracking.html?AWB=${n}&brand=DHL`,
  },
  // Delhivery: starts with DL or DEL
  {
    pattern: /^(DL|DEL)\d+/,
    code: "Delhivery",
    buildUrl: (n) => `https://www.delhivery.com/tracking/?tracking_id=${n}`,
  },
  // Blue Dart: starts with BD + digits + optional IN
  {
    pattern: /^BD\d{9}(IN)?$/,
    code: "Blue Dart",
    buildUrl: (n) => `https://www.bluedart.com/tracking/${n}`,
  },
  // DTDC: starts with Z + digits
  {
    pattern: /^Z\d+$/,
    code: "DTDC",
    buildUrl: (n) =>
      `https://tracking.dtdc.com/ctbs-tracking/customerInterface.tr?submitName=showCustInterface&cnNo=${n}`,
  },
  // XpressBees: starts with XB + digits
  {
    pattern: /^XB\d+$/,
    code: "XpressBees",
    buildUrl: (n) =>
      `https://www.xpressbees.com/shipment/tracking/?awb=${n}`,
  },
  // Ecom Express: starts with E + 10 digits
  {
    pattern: /^E\d{10}$/,
    code: "Ecom Express",
    buildUrl: (n) => `https://ecomexpress.in/tracking/?awb_field=${n}`,
  },
];

/**
 * Returns the carrier tracking page URL for a given tracking number and
 * optional carrier name hint.
 *
 * Always returns a URL — falls back to Google Search so the user is never
 * left with nothing.
 */
export function getCarrierTrackingUrl(
  trackingNumber: string,
  carrierName?: string,
): string {
  const num = trackingNumber.trim().toUpperCase();
  const nameLower = (carrierName ?? "").toLowerCase().trim();

  // 1. Match by carrier name
  if (nameLower) {
    for (const entry of CARRIER_NAME_MAP) {
      if (entry.keywords.some((kw) => nameLower.includes(kw))) {
        return entry.buildUrl(num);
      }
    }
  }

  // 2. Match by tracking number pattern
  for (const entry of PATTERN_MAP) {
    if (entry.pattern.test(num)) {
      return entry.buildUrl(num);
    }
  }

  // 3. Google Search fallback
  return `https://www.google.com/search?q=${encodeURIComponent(trackingNumber + " tracking")}`;
}

/**
 * Returns a friendly carrier display name derived from the carrier name string
 * or the tracking number pattern.
 */
export function detectCarrierName(
  trackingNumber: string,
  carrierName?: string,
): string {
  if (carrierName?.trim()) return carrierName.trim();

  const num = trackingNumber.trim().toUpperCase();
  for (const entry of PATTERN_MAP) {
    if (entry.pattern.test(num)) return entry.code;
  }
  return "Courier";
}
