/**
 * Posts and replies keep their text in two columns (`<prefix>_ar` /
 * `<prefix>_en`), and older records fill only one of them. Readers fall back
 * to the other side (`pickLocalized`), so the editor has to as well — and the
 * save has to land where readers look: an Arabic-only post edited from the
 * English interface used to write only `_en`, so Arabic readers kept seeing
 * the old text (`PostController@update` / `ReplyController@update` keep the
 * column that is not sent).
 */
type TextRecord = Record<string, unknown> | null | undefined;

const text = (record: TextRecord, key: string) => {
  const value = record?.[key];
  return typeof value === "string" ? value : "";
};

const columns = (prefix: string, language: string) => {
  const own = `${prefix}_${language === "ar" ? "ar" : "en"}`;
  const other = `${prefix}_${language === "ar" ? "en" : "ar"}`;
  return { own, other };
};

/** The text the editor opens with: the interface language, else the other side. */
export function editableText(record: TextRecord, prefix: string, language: string): string {
  const { own, other } = columns(prefix, language);
  return text(record, own) || text(record, other);
}

/**
 * The columns a save writes: the interface language, plus the other side when
 * that is where the edited text came from (the interface side was empty).
 */
export function textColumnsToWrite(record: TextRecord, prefix: string, language: string): string[] {
  const { own, other } = columns(prefix, language);
  return !text(record, own).trim() && text(record, other).trim() ? [own, other] : [own];
}
