/** Sentinels for `ts_headline` — swapped to `<mark>` only after HTML escape. */
export const HEADLINE_START_SEL = '⟦'
export const HEADLINE_STOP_SEL = '⟧'

/** Options object for Postgres `ts_headline` matching the sentinel pair. */
export const HEADLINE_OPTS = {
  StartSel: HEADLINE_START_SEL,
  StopSel: HEADLINE_STOP_SEL,
} as const

function escapeHtml(fragment: string): string {
  return fragment
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}

/**
 * XSS-safe `ts_headline` HTML: escape first, then swap sentinels to `<mark>`.
 */
export function buildSafeHeadlineHtml(fragment: string): string {
  const escaped = escapeHtml(fragment)
  return escaped
    .replaceAll(HEADLINE_START_SEL, '<mark>')
    .replaceAll(HEADLINE_STOP_SEL, '</mark>')
}
