import { computed, ref } from 'vue'
import { dummyExternalSystems } from '../data/dummy-external-systems'
import {
  externalSystemStatusLabel,
  getExternalSystemStatus,
} from '../utils/external-system.utils'
import type { ExternalSystem } from '../types/external-system.types'

export function useExternalSystemList() {
  const search = ref('')
  const loading = ref(false)

  const systems = computed(() => {
    const query = search.value.trim().toLowerCase()
    if (!query) {
      return dummyExternalSystems
    }

    return dummyExternalSystems.filter((system) => {
      const haystack = [
        system.name,
        system.code,
        system.description,
        externalSystemStatusLabel(getExternalSystemStatus(system)),
      ]
        .join(' ')
        .toLowerCase()

      return haystack.includes(query)
    })
  })

  const availableCount = computed(
    () => systems.value.filter((system) => getExternalSystemStatus(system) === 'available').length,
  )

  function getSystemById(id: string): ExternalSystem | undefined {
    return dummyExternalSystems.find((system) => system.id === id)
  }

  return {
    systems,
    search,
    loading,
    availableCount,
    getSystemById,
  }
}
