/**
 * The backend's choice tables (`GET /choices/{type}/`) and the dropdown
 * options built from them.
 *
 * Nine hooks were each re-declaring the same `(item: any) => ({ label, value })`
 * map over this payload. The duplication is why the id coercion had drifted:
 * some call sites send the raw numeric `id`, others `String(item.id)`. The
 * helpers here keep the mapping in one place and take the id projection as an
 * argument, so each caller keeps the coercion it already had instead of being
 * silently migrated onto a different one — see `CHOICE_ID_COERCION` below.
 */

/**
 * One row of a choice table.
 *
 * Verified against `BaseController::choices()`, which projects exactly these
 * four keys. `id` is `master_choices.id` — `$table->id()`, so an integer; five
 * local copies of this interface used to declare it `string`, and three call
 * sites compensated with `String(item.id)`. The endpoint returns an *error*
 * envelope rather than an empty list when the choice type has no rows, so
 * every reader must tolerate a missing `data` — which is what the `|| []` in
 * the helpers below is for.
 */
export interface ChoiceItem {
  license_required?: boolean;
  license_document_required?: boolean;
  is_active?: boolean;
  id: number;
  value_en: string;
  value_ar: string;
  /** Added by the BE-62 migration; absent on rows created before it. */
  slug?: string | null;
}

/**
 * A choice as it appears *embedded in another record*, under a `*_display`
 * key — `gender_display`, `format_display`, `learning_type_display` and so on.
 *
 * Verified against `ResolvesApiPayloads::masterChoicePayload()`, which returns
 * exactly these five keys or `null` when the relation is unset — so a reader
 * must handle the whole object being absent, not just individual fields. `id`
 * is the same `master_choices.id` integer as on `ChoiceItem`; three of the
 * five local copies this replaces declared it `string`, which is how the
 * learn-&-serve edit comparison bug survived review.
 *
 * A collection of these (`interest_display` and friends, built by
 * `masterChoiceCollection`) is `null` rather than `[]` when empty.
 */
export interface ChoiceDisplay {
  id?: number | null;
  /** The choice table this row belongs to, e.g. `"gender"`. */
  choice_type?: string | null;
  value_en?: string | null;
  value_ar?: string | null;
  slug?: string | null;
}

/**
 * What a dropdown option's `value` may hold.
 *
 * `string | number` is not a convenience: the choice endpoints return numeric
 * ids and most call sites forward them unconverted, so the narrower
 * `value: string` the inputs used to declare was simply inaccurate.
 */
export type ChoiceValue = string | number;

/**
 * A known inconsistency, recorded rather than changed.
 *
 * Gender and relationship dropdowns submit the numeric `id`; the org-type
 * dropdowns submit `String(id)`; the interest checkboxes use a numeric id in
 * the profile forms and a string id in the volunteer-opportunity form. Each
 * form is internally consistent — the value it stores and the value it
 * compares against are the same type — so nothing is broken today, but the
 * four conventions should be unified once the submitted payloads can be
 * re-tested against the backend.
 */
export const CHOICE_ID_COERCION = "per-call-site" as const;

/**
 * A choice id in the form a Formik string field holds.
 *
 * The two sides of every `values.x === someChoiceId` comparison have to agree
 * on this, and they used not to: the dropdown option carried the raw integer
 * while `*_display.id?.toString()` seeded the form with a string, so the
 * comparison was `3 === "3"` on every edit. Both sides now call one of these
 * two functions, which cannot disagree.
 *
 * Covered by `tests/learnServeChoiceIds.test.ts`.
 */
export function choiceFormValue(item: ChoiceItem): string {
  return String(item.id);
}

/** The same projection for a choice embedded under a `*_display` key. */
export function displayFormValue(display?: ChoiceDisplay | null): string {
  return display?.id?.toString() ?? "";
}

/** The label for a choice row in the active language. */
export function choiceLabel(item: ChoiceItem, language: string): string {
  return language === "ar" ? item.value_ar : item.value_en;
}

/**
 * `SelectInput` / `GroupedSelectInput` options.
 *
 * `rawValue` carries the unlocalized `value_en`, which the org-type rules read
 * to decide licence and visibility behaviour; it is always populated so those
 * rules never depend on the active language.
 */
export function toChoiceOptions<V extends ChoiceValue>(
  items: ChoiceItem[] | undefined,
  language: string,
  toValue: (item: ChoiceItem) => V
): { label: string; value: V; rawValue: string; licenseRequired?: boolean; licenseDocumentRequired?: boolean }[] {
  return (
    items?.map((item) => ({
      label: choiceLabel(item, language),
      value: toValue(item),
      rawValue: item.value_en,
      licenseRequired: item.license_required,
      licenseDocumentRequired: item.license_document_required,
    })) || []
  );
}

/** `TagsCheckbox` options, which key on `id` rather than `value`. */
export function toChoiceTagOptions<I extends ChoiceValue>(
  items: ChoiceItem[] | undefined,
  language: string,
  toId: (item: ChoiceItem) => I
): { id: I; label: string }[] {
  return (
    items?.map((item) => ({
      id: toId(item),
      label: choiceLabel(item, language),
    })) || []
  );
}
