import { activeClubMemberships } from './activeClub'

function userIsClubAdminForClub(user, clubId) {
  if (clubId == null || user == null) return false
  const cid = Number(clubId)
  const row = activeClubMemberships(user.clubs).find((c) => Number(c.id) === cid)
  return Array.isArray(row?.roles) && row.roles.includes('club_admin')
}

function userHasAnyClubAdminRole(user) {
  return activeClubMemberships(user?.clubs).some((c) => Array.isArray(c.roles) && c.roles.includes('club_admin'))
}

/**
 * Ob die Löschen-Aktion in der Liste sinnvoll angeboten werden kann (Server hat letzte Instanz).
 */
export function canUserRequestExerciseDelete(user, exercise) {
  if (!user || !exercise) return false
  const role = String(user.role || '').toLowerCase()
  if (role === 'admin' || role === 'superadmin') return true
  const vis = exercise.visibility || 'private'
  const mine = Number(exercise.created_by) === Number(user.id)
  if (vis === 'official') return false
  if (vis === 'club') {
    return userIsClubAdminForClub(user, exercise.club_id)
  }
  if (mine) return true
  return userHasAnyClubAdminRole(user)
}
