import { z } from "zod"

import { Lang } from "@/constants/languages"

export const languageSchema = z.preprocess(
  (arg) => (typeof arg === "string" ? arg.toLowerCase() : arg),
  z.nativeEnum(Lang)
)

export function isValidLang(lang?: string): lang is Lang {
  const result = languageSchema.safeParse(lang)
  return result.success
}

export function findLang(pathname: string): Lang | undefined {
  const langFromPath = Object.values(Lang).find(
    (l) => pathname.startsWith(`/${l}/`) || pathname === `/${l}`
  )

  return isValidLang(langFromPath) ? langFromPath : undefined
}
