/**
 * EDR run-number pairs, keyed by the odd EXPORT run (Ethiopia → Djibouti). The
 * even IMPORT run (Djibouti → Ethiopia) is fixed by the export run, so choosing
 * an export number fully determines the import one.
 *
 * Run numbers are always 4 digits (8401, never 84001). Pairs are listed out
 * rather than computed from the 8001/+100/+1 pattern, so a run that ever breaks
 * the convention stays correct here.
 *
 * Mirrors RUN_WAGONS/IMPORT_RUN in the API's SeedWagonRunNumbers migration —
 * keep the two in sync when runs are added or retired.
 */
export const TRAIN_RUN_PAIRS: Record<string, string> = {
  "8001": "8002",
  "8101": "8102",
  "8201": "8202",
  "8301": "8302",
  "8401": "8402",
  "8501": "8502",
  "8601": "8602",
  "8701": "8702",
  "8801": "8802",
  "8901": "8902",
  "9001": "9002",
};

/** Even IMPORT run -> its odd EXPORT run. Derived so the two cannot drift. */
const EXPORT_BY_IMPORT: Record<string, string> = Object.fromEntries(
  Object.entries(TRAIN_RUN_PAIRS).map(([exportRun, importRun]) => [importRun, exportRun]),
);

/** Selectable export runs (odd), in run order. */
export const EXPORT_TRAIN_OPTIONS = Object.keys(TRAIN_RUN_PAIRS).map((run) => ({
  label: run,
  value: run,
}));

/** Selectable import runs (even), in run order. */
export const IMPORT_TRAIN_OPTIONS = Object.values(TRAIN_RUN_PAIRS).map((run) => ({
  label: run,
  value: run,
}));

/**
 * Options for filtering a list by run — one entry per pair, labelled
 * "export-import" (8001-8002). The value is the odd EXPORT run, which uniquely
 * identifies the pair; the API matches a wagon whose export OR import run
 * equals it, so the whole train's wagons come back.
 */
export const TRAIN_RUN_FILTER_OPTIONS = Object.entries(TRAIN_RUN_PAIRS).map(
  ([exportRun, importRun]) => ({
    label: `${exportRun}-${importRun}`,
    value: exportRun,
  }),
);

/**
 * The import run implied by an export run; empty string when unset/unknown.
 * Runs outside the hardcoded pairs (admin-added via dropdown settings) fall
 * back to the numeric convention: import = export + 1.
 */
export const importRunFor = (exportRun: unknown): string => {
  const run = String(exportRun ?? "");
  const paired = TRAIN_RUN_PAIRS[run];
  if (paired) return paired;
  return /^\d*[13579]$/.test(run) ? String(Number(run) + 1) : "";
};

/**
 * The export run implied by an import run; empty string when unset/unknown.
 * Runs outside the hardcoded pairs (admin-added via dropdown settings) fall
 * back to the numeric convention: export = import − 1.
 */
export const exportRunFor = (importRun: unknown): string => {
  const run = String(importRun ?? "");
  const paired = EXPORT_BY_IMPORT[run];
  if (paired) return paired;
  return /^\d*[02468]$/.test(run) && Number(run) > 0 ? String(Number(run) - 1) : "";
};
