import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { getExternalSystem } from '../services/external-system.service'
import {
  getExternalSystemStatus,
  isExternalSystemAccessible,
} from '../utils/external-system.utils'
import type { ExternalSystem } from '../types/external-system.types'

export function useExternalSystemDetail() {
  const route = useRoute()

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

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

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

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

  async function fetchSystem(id: string) {
    loading.value = true
    error.value = null

    try {
      system.value = await getExternalSystem(id)
    } catch (err) {
      system.value = null
      error.value = getApiErrorMessage(err, 'Sistem luaran tidak dijumpai.')
    } finally {
      loading.value = false
    }
  }

  watch(
    systemId,
    (id) => {
      if (!id) {
        system.value = null
        error.value = 'Sistem luaran tidak dijumpai.'
        return
      }

      fetchSystem(id)
    },
    { immediate: true },
  )

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