import { activeClubMemberships } from './activeClub'

export function clubAdminInClub(user, clubId) {
  const cid = Number(clubId)
  if (!Number.isFinite(cid)) return false
  const row = activeClubMemberships(user?.clubs).find((c) => Number(c.id) === cid)
  return Boolean(row?.roles?.includes('club_admin'))
}

/**
 * Löschen von Bibliotheks-/Planungsinhalten (Vorlage, Modul, Rahmen, Graph) — grob wie Backend club_tenancy.
 * Vereins-Admins können fremde private Einträge im API löschen (gemeinsamer Verein); das blenden wir hier nicht ein.
 */
/** Bearbeiten — grob wie Backend assert_library_content_editable (Ersteller, Plattform, Planung im Verein). */
export function canEditLibraryContent(user, row) {
  const grole = String(user?.role || '').toLowerCase()
  if (grole === 'admin' || grole === 'superadmin') return true
  const uid = Number(user?.id)
  if (!Number.isFinite(uid)) return false

  const vis = String(row?.visibility ?? 'club').toLowerCase()
  const createdBy = row?.created_by != null ? Number(row.created_by) : null
  const clubId = row?.club_id != null ? Number(row.club_id) : null

  if (vis === 'official') return false
  if (Number.isFinite(createdBy) && createdBy === uid) return true
  if (vis === 'club' && Number.isFinite(clubId)) {
    return activeClubMemberships(user?.clubs).some((c) => Number(c.id) === clubId)
  }
  return false
}

export function canDeleteLibraryContent(user, row) {
  const grole = String(user?.role || '').toLowerCase()
  if (grole === 'admin' || grole === 'superadmin') return true
  const uid = Number(user?.id)
  if (!Number.isFinite(uid)) return false

  const vis = String(row?.visibility ?? 'club').toLowerCase()
  const createdBy = row?.created_by != null ? Number(row.created_by) : null
  const clubId = row?.club_id != null ? Number(row.club_id) : null

  if (vis === 'official') return false
  if (vis === 'club') return clubAdminInClub(user, clubId)
  if (vis === 'private') return Number.isFinite(createdBy) && createdBy === uid
  return false
}
