// Cannot use from "@/constants/languages" due to jiti
import { Lang } from "../constants/languages"

export function getLiveStatus(
  internalEnv:
    | {
        NEW_SITE_LIVE_FOR_LANGS: string[]
      }
    | {
        NEXT_PUBLIC_NEW_SITE_LIVE_FOR_LANGS: string[]
      }
): "ALL_LANGUAGES_LIVE" | "SOME_LANGUAGES_LIVE" | "NOT_LIVE" {
  const configuredLangs = getConfiguredLangs(internalEnv)
  if (!configuredLangs) {
    return "NOT_LIVE"
  }

  const allLangs = Object.keys(Lang)
  const liveLangs = allLangs.filter((lang) => configuredLangs.includes(lang))
  if (liveLangs.length === 0) {
    return "NOT_LIVE"
  }

  if (
    liveLangs.length === allLangs.length &&
    allLangs.every((lang) => liveLangs.includes(lang))
  ) {
    return "ALL_LANGUAGES_LIVE"
  }

  return "SOME_LANGUAGES_LIVE"
}

function getConfiguredLangs<T extends {}>(env: T): string[] | undefined {
  if (
    !(
      "NEW_SITE_LIVE_FOR_LANGS" in env ||
      "NEXT_PUBLIC_NEW_SITE_LIVE_FOR_LANGS" in env
    )
  ) {
    return undefined
  }

  const configuredLangs =
    "NEW_SITE_LIVE_FOR_LANGS" in env
      ? env.NEW_SITE_LIVE_FOR_LANGS
      : env.NEXT_PUBLIC_NEW_SITE_LIVE_FOR_LANGS

  if (!Array.isArray(configuredLangs)) {
    throw new Error("Misconfigured environment variable, expected array")
  }

  return configuredLangs
}
