import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export function useQueryCRUDMode(key: string = 'mode') {
  const route = useRoute()
  const router = useRouter()

  const mode = computed<'list' | 'entry'>({
    get: () => (route.query[key] && route.query[key] === 'entry' ? 'entry' : 'list'),
    set: (val) => {
      router.push({
        path: route.path,
        query: {
          ...route.query,
          [key]: val,
        },
      })
    },
  })

  const goToEntry = () => (mode.value = 'entry')
  const backToList = () =>(mode.value = 'list')

  return { mode, goToEntry, backToList }
}

export function useQueryCRUDRecordId(key: string = 'record-id') {
  const route = useRoute()
  const router = useRouter()

  // const recordId = useState('route-query-' + key, () => '')
  const recordId = computed({
    get: () => route.query[key],
    set: (val: string) => {
      router.replace({
        path: route.path,
        query: {
          ...route.query,
          [key]: val,
        },
      })
    },
  })

  return { recordId }
}
