import type { RouteLocationNormalizedLoaded, Router } from 'vue-router'

export interface ListQueryFilters {
  [key: string]: string | string[] | undefined
}

export function useAdminListQuerySync(route: RouteLocationNormalizedLoaded, router: Router) {
  function readQueryString(key: string): string {
    const value = route.query[key]
    const rawValue = Array.isArray(value) ? value[0] : value
    return typeof rawValue === 'string' ? rawValue.trim() : ''
  }

  function readQueryPage(): number {
    const page = Number(readQueryString('page'))
    return Number.isInteger(page) && page > 0 ? page : 1
  }

  async function syncRouteQuery(page: number, filters: ListQueryFilters = {}) {
    const query: Record<string, string> = {}
    if (page > 1) { query.page = String(page) }
    for (const [key, value] of Object.entries(filters)) {
      const trimmed = (Array.isArray(value) ? value.join(',') : value)?.trim()
      if (trimmed) { query[key] = trimmed }
    }
    await router.replace({ path: route.path, query })
  }

  return { readQueryString, readQueryPage, syncRouteQuery }
}
