import { cloneDeep } from 'lodash-es'
import { type Reactive, ref, type Ref, toRef, watch } from 'vue'

export function usePrevious<T>(value: T | Ref<T> | Reactive<T>) {
  const currentValue = toRef(value)
  const previousValue = ref<T>(cloneDeep(currentValue.value))

  watch(
    () => currentValue.value,
    (_v, oldValue) => {
      previousValue.value = oldValue
    }
  )

  return {
    currentValue,
    previousValue
  }
}
