import { HashNavEntry } from '@/widgets/base/types/HashNavEntry'
import { HashNavRoute } from '@/widgets/base/types/HashNavRoute'
import { match, compile } from 'path-to-regexp'

export function buildHashNavRoutes<N extends string>(list: HashNavEntry<N>[]) {
  const result = {} as { [k in N]: HashNavRoute<k> }

  for (const entry of list) {
    result[entry.pageName] = buildHashNavRoute(entry)
  }

  return result
}

function buildHashNavRoute<N extends string>(
  entry: HashNavEntry<N>
): HashNavRoute<N> {
  const matchFn = match(entry.path)
  const compileFn = compile(entry.path)

  return {
    layoutName: entry.layoutName,
    pageName: entry.pageName,
    match: (hash: string) => {
      const result = matchFn(hash)
      return result ? (result.params as Record<string, string>) : result
    },
    compile: (params: Record<string, string> = {}) => compileFn(params),
  }
}
