import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useExternalSystemList } from './useExternalSystemList'
import {
  getExternalSystemStatus,
  isExternalSystemAccessible,
} from '../utils/external-system.utils'

export function useExternalSystemDetail() {
  const route = useRoute()
  const { getSystemById } = useExternalSystemList()

  const loading = ref(false)
  const error = ref<string | null>(null)

  const systemId = computed(() => String(route.params.id ?? ''))

  const system = computed(() => getSystemById(systemId.value) ?? null)

  const status = computed(() => (system.value ? getExternalSystemStatus(system.value) : null))

  const isAccessible = computed(() =>
    system.value ? isExternalSystemAccessible(system.value) : false,
  )

  watch(
    systemId,
    () => {
      error.value = system.value ? null : 'Sistem luaran tidak dijumpai.'
    },
    { immediate: true },
  )

  return {
    system,
    loading,
    error,
    status,
    isAccessible,
  }
}
