import type { Ref } from 'vue'

interface UsedInMachine {
  id: string
  name: string
  site?: { id: string; name: string } | null
}

interface UsedInEntity {
  id: string
  name: string
}

interface UsedInData {
  machines: UsedInMachine[]
  composants: UsedInEntity[]
  pieces: UsedInEntity[]
}

export function useUsedIn(entityType: Ref<'composants' | 'pieces' | 'products'>, entityId: Ref<string | null>) {
  const data = ref<UsedInData>({ machines: [], composants: [], pieces: [] })
  const loading = ref(false)

  const api = useApi()

  const load = async () => {
    if (!entityId.value) return
    loading.value = true
    try {
      const result = await api.get(`/${entityType.value}/${entityId.value}/used-in`)
      if (result.success && result.data) {
        data.value = {
          machines: result.data.machines || [],
          composants: result.data.composants || [],
          pieces: result.data.pieces || [],
        }
      }
    } finally {
      loading.value = false
    }
  }

  const totalCount = computed(() =>
    data.value.machines.length + data.value.composants.length + data.value.pieces.length
  )

  watch(entityId, (val) => {
    if (val) load()
  }, { immediate: true })

  return { data, loading, totalCount, load }
}
