package de.trainingstagebuch.app.utils

import de.trainingstagebuch.app.repository.MemberItem

enum class MembersSortOrder {
    NameAsc,
    NameDesc,
    Status
}

object MembersFilterUtils {
    fun apply(
        members: List<MemberItem>,
        searchQuery: String,
        showInactive: Boolean,
        sortOrder: MembersSortOrder
    ): List<MemberItem> {
        val query = searchQuery.trim().lowercase()
        val filtered = members.filter { member ->
            val activeMatches = showInactive || member.active
            val queryMatches = query.isBlank() || member.displayName.lowercase().contains(query)
            activeMatches && queryMatches
        }

        return when (sortOrder) {
            MembersSortOrder.NameAsc -> filtered.sortedBy { it.displayName.lowercase() }
            MembersSortOrder.NameDesc -> filtered.sortedByDescending { it.displayName.lowercase() }
            MembersSortOrder.Status -> filtered.sortedWith(
                compareBy<MemberItem> { statusRank(it) }
                    .thenBy { it.displayName.lowercase() }
            )
        }
    }

    private fun statusRank(item: MemberItem): Int {
        return when {
            item.active && !item.testMembership -> 0
            item.active && item.testMembership -> 1
            else -> 2
        }
    }
}
