import type { Freight } from "@edr/types";

import { REQUIRED_DOC_FIELDS } from "../BookingDetailPage/constants";

/** A single uploaded file on a booking. */
export type BookingFile = NonNullable<Freight.IBooking["files"]>[number];

/** Human labels for known document codes (shipment + onboarding documents). */
const LABEL_BY_CODE = new Map<string, string>([
  ...REQUIRED_DOC_FIELDS.map((d) => [d.key, d.label] as const),
  // Company onboarding document codes (see file-upload-settings seeder).
  ["tin_certificate", "TIN Certificate"],
  ["commercial_license", "Commercial Registration"],
  ["business_license", "Business License / Trade License"],
  ["investment_license", "Investment License"],
  ["national_id", "National ID"],
  ["national_id_passport", "National ID / Passport"],
  ["passport", "Passport"],
]);

/**
 * Turn a file `code` (e.g. "tin_certificate", "commercial_invoice",
 * "custom_172..._0") into a human label. Known codes use their configured label;
 * ad-hoc / unknown codes are title-cased from the code itself.
 */
export function labelForDocCode(code: string): string {
  const known = LABEL_BY_CODE.get(code);
  if (known) return known;
  // Profile documents carried onto a contract are suffixed per file
  // ("business_license_2") — label from the base code, numbered past the first.
  const base = code.replace(/_\d+$/, "");
  const baseLabel = LABEL_BY_CODE.get(base);
  if (baseLabel) {
    const n = code.slice(base.length + 1);
    return n && n !== "1" ? `${baseLabel} ${n}` : baseLabel;
  }
  return code
    .replace(/^custom_\d+_\d+$/, "Additional document")
    .replace(/[_-]+/g, " ")
    .replace(/\b\w/g, (c) => c.toUpperCase());
}
