// Generic plan code formatter for SIM plans
// Examples:
//  - PASI_10G -> 10G
//  - PASI_25G -> 25G
//  - ANY_PREFIX_50GB -> 50G
//  - Fallback: return the original code when unknown

export function formatPlanShort(planCode?: string): string {
  if (!planCode) return "—";
  const m = planCode.match(/(?:^|[_-])(\d+(?:\.\d+)?)\s*G(?:B)?\b/i);
  if (m && m[1]) {
    return `${m[1]}G`;
  }
  // Try extracting trailing number+G anywhere in the string
  const m2 = planCode.match(/(\d+(?:\.\d+)?)\s*G(?:B)?\b/i);
  if (m2 && m2[1]) {
    return `${m2[1]}G`;
  }
  return planCode;
}

// Mapping between Freebit plan codes and Salesforce product SKUs used by the portal
export const SIM_PLAN_SKU_BY_CODE: Record<string, string> = {
  PASI_5G: "SIM-DATA-VOICE-5GB",
  PASI_10G: "SIM-DATA-VOICE-10GB",
  PASI_25G: "SIM-DATA-VOICE-25GB",
  PASI_50G: "SIM-DATA-VOICE-50GB",
  PASI_5G_DATA: "SIM-DATA-ONLY-5GB",
  PASI_10G_DATA: "SIM-DATA-ONLY-10GB",
  PASI_25G_DATA: "SIM-DATA-ONLY-25GB",
  PASI_50G_DATA: "SIM-DATA-ONLY-50GB",
};

export function getSimPlanSku(planCode?: string): string | undefined {
  if (!planCode) return undefined;
  return SIM_PLAN_SKU_BY_CODE[planCode];
}

/**
 * Map Freebit plan codes to simplified format for API requests
 * Converts PASI_5G -> 5GB, PASI_25G -> 25GB, etc.
 */
export function mapToSimplifiedFormat(planCode?: string): string {
  if (!planCode) return "";
  
  // Handle Freebit format (PASI_5G, PASI_25G, etc.)
  if (planCode.startsWith("PASI_")) {
    const match = planCode.match(/PASI_(\d+)G/);
    if (match) {
      return `${match[1]}GB`;
    }
  }
  
  // Handle other formats that might end with G or GB
  const match = planCode.match(/(\d+)\s*G(?:B)?\b/i);
  if (match) {
    return `${match[1]}GB`;
  }
  
  // Return as-is if no pattern matches
  return planCode;
}
