import { computed, ref } from 'vue'
import type { CrudListQuery } from './contracts'

export function useCrudListState(initial: CrudListQuery) {
  const query = ref<CrudListQuery>({ ...initial, sorts: [...initial.sorts], filters: [...initial.filters] })
  const selectedId = ref<string | number | null>(null)
  const dirty = ref(false)

  function replace(next: CrudListQuery): void { query.value = { ...next, sorts: [...next.sorts], filters: [...next.filters] } }
  function setPage(page: number, pageSize = query.value.pageSize): void { query.value = { ...query.value, page, pageSize } }
  function setSearch(search?: string): void { query.value = { ...query.value, page: 1, search: search?.trim() || undefined } }
  function reset(): void { replace(initial); selectedId.value = null; dirty.value = false }

  return {
    query,
    selectedId,
    dirty,
    offset: computed(() => (query.value.page - 1) * query.value.pageSize),
    replace,
    setPage,
    setSearch,
    reset
  }
}
