// ── Field tooltips (lsc_tooltips) ─────────────────────────────────────────────
// Admin-editable field hints loaded from the lsc_tooltips table (KAR-700).
// Pure resolve/map helpers are unit-tested; loadTooltips does the I/O.

import type { SupabaseClient } from '@supabase/supabase-js'
import type { Locale } from '@/lib/i18n/i18n-context'

export interface TooltipRow {
  tooltip_key: string
  label_de: string | null
  label_en: string | null
  content_de: string | null
  content_en: string | null
  formula: string | null
  example: string | null
}

export interface FieldHintData {
  key: string
  label: string
  content: string
  formula: string | null
  example: string | null
}

const TOOLTIP_COLUMNS =
  'tooltip_key, label_de, label_en, content_de, content_en, formula, example'

/**
 * Resolve a raw tooltip row to a single locale. English uses the *_en columns;
 * everything else (de/es/zh) falls back to German, which is the seeded source
 * language. Empty label falls back to the key so a tooltip is never blank.
 */
export function resolveTooltip(row: TooltipRow, locale: Locale): FieldHintData {
  const en = locale === 'en'
  const label = (en ? row.label_en : row.label_de) ?? row.label_de ?? row.tooltip_key
  const content = (en ? row.content_en : row.content_de) ?? row.content_de ?? ''
  return { key: row.tooltip_key, label, content, formula: row.formula, example: row.example }
}

/** Build a key → resolved-hint map for the given locale. */
export function buildTooltipMap(
  rows: TooltipRow[],
  locale: Locale,
): Record<string, FieldHintData> {
  const map: Record<string, FieldHintData> = {}
  for (const row of rows) {
    map[row.tooltip_key] = resolveTooltip(row, locale)
  }
  return map
}

/**
 * Load tooltip rows, optionally filtered by key prefix (e.g. 'workshop.').
 * Throws on error — a silently-empty hint set would hide config problems.
 */
export async function loadTooltips(
  supabase: SupabaseClient,
  keyPrefix?: string,
): Promise<TooltipRow[]> {
  let query = supabase.from('lsc_tooltips').select(TOOLTIP_COLUMNS)
  if (keyPrefix) query = query.like('tooltip_key', `${keyPrefix}%`)
  const { data, error } = await query
  if (error) throw new Error(`Feld-Hinweise konnten nicht geladen werden: ${error.message}`)
  return (data ?? []) as TooltipRow[]
}
