import { computed } from 'vue'
import type { Ref } from 'vue'
import { store } from '../store'

// Common filters, refactored for reuse.
export function use_filtered_data(
    is_live_debounced: Ref<boolean>,
    timeline_position_debounced: Ref<number>
) {
    const visible_alarms = computed(() => {
        if (is_live_debounced.value) return store.alarms
        const cutoff = timeline_position_debounced.value / 1000
        return store.alarms.filter(a => new Date(a.created + ' UTC').getTime() / 1000 <= cutoff)
    })

    const visible_incidents = computed(() => {
        if (is_live_debounced.value) return store.incidents
        const cutoff = timeline_position_debounced.value / 1000
        return store.incidents.filter(a => new Date(a.created + ' UTC').getTime() / 1000 <= cutoff)
    })

    const filtered_alarms = computed(() => {
        const sorted = [...visible_alarms.value].sort((a, b) =>
            new Date(b.created + ' UTC').getTime() - new Date(a.created + ' UTC').getTime()
        )
        if (store.severity_filter === null) return sorted
        return sorted.filter(a => a.severity === store.severity_filter)
    })

    const filtered_incidents = computed(() => {
        const sorted = [...visible_incidents.value].sort((a, b) =>
            new Date(b.created + ' UTC').getTime() - new Date(a.created + ' UTC').getTime()
        )
        if (store.severity_filter === null) return sorted
        return sorted.filter(a => a.severity === store.severity_filter)
    })

    return { visible_alarms, visible_incidents, filtered_alarms, filtered_incidents }
}
