import { ACTIVE_CLUB_STORAGE_KEY } from './api'

/** Nur Mitgliedschaften mit aktivem Vereinszugang (Backend: club_members.status). */
export function activeClubMemberships(clubs) {
  return (clubs || []).filter(
    (c) => (c.membership_status || 'active').toString().trim().toLowerCase() === 'active'
  )
}

/**
 * Einheitliche Anzeige des aktiven Vereins: Abgleich mit effective_club_id, active_club_id,
 * LocalStorage (Request-Header-Quelle), sonst erster **aktiver** Verein der Liste.
 */
export function getResolvedActiveClubIdForUi(user) {
  const clubs = activeClubMemberships(user?.clubs)
  if (!clubs.length) return null

  const idInClubs = (id) =>
    id != null &&
    id !== '' &&
    clubs.some((c) => Number(c.id) === Number(id))

  const eff = user?.effective_club_id
  if (idInClubs(eff)) return Number(eff)

  const ac = user?.active_club_id
  if (idInClubs(ac)) return Number(ac)

  try {
    const ls = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
    if (ls && /^\d+$/.test(ls.trim()) && clubs.some((c) => String(c.id) === ls.trim())) {
      return Number(ls.trim())
    }
  } catch {
    /* ignore */
  }

  return Number(clubs[0].id)
}

/**
 * Fallback für Formulare (Vereins-Sichtbarkeit): wie getResolvedActiveClubIdForUi, aber wenn der
 * Nutzer keiner Mitgliedschaft-Vereinsliste angehört, nutzt ein Plattform-Admin weiterhin das in
 * effective_club_id / active_club_id gespeicherte Mandantenziel (wie X-Active-Club-Id).
 */
export function getDefaultClubIdForGovernanceForms(user) {
  const viaMembership = getResolvedActiveClubIdForUi(user)
  if (viaMembership != null) return viaMembership

  const role = String(user?.role || '').toLowerCase()
  if (role !== 'admin' && role !== 'superadmin') return null

  const rawEc = user?.effective_club_id
  const rawAc = user?.active_club_id
  const nEc = rawEc !== null && rawEc !== '' ? Number(rawEc) : NaN
  const nAc = rawAc !== null && rawAc !== '' ? Number(rawAc) : NaN
  if (Number.isFinite(nEc) && nEc > 0) return nEc
  if (Number.isFinite(nAc) && nAc > 0) return nAc
  try {
    const ls = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
    const nLs = ls && /^\d+$/.test(ls.trim()) ? Number(ls.trim()) : NaN
    if (Number.isFinite(nLs) && nLs > 0) return nLs
  } catch {
    /* ignore */
  }
  return null
}

/** Für useEffect-/Query-Deps: Änderungen am Mandanten-Vereins-Kontext sollen Daten neu laden. */
export function getTenantClubDependencyKey(user) {
  const m = getResolvedActiveClubIdForUi(user)
  if (m != null) return String(m)
  const d = getDefaultClubIdForGovernanceForms(user)
  return d != null ? String(d) : 'none'
}
