/**
 * Transforms an unknown error to an error message string.
 */
export function unknownToErrorMessage(error: unknown, message: string): string {
  return `${message}: ${error instanceof Error ? error.message : JSON.stringify(error)}`
}

/**
 * Makes sure that the URL always ends with a slash.
 */
export const normalizeUrl = (url: string): string => {
  return url.endsWith('/') ? url : `${url}/`
}

/**
 * Parses role/group lists from JSON-array or CSV strings.
 */
export function parseStringList(raw: unknown, fallback: string[] = []): string[] {
  if (typeof raw !== 'string' || raw.trim().length === 0) {
    return fallback
  }

  try {
    const parsed = JSON.parse(raw)
    if (Array.isArray(parsed)) {
      return parsed
        .filter((entry): entry is string => typeof entry === 'string')
        .map((entry) => entry.trim())
        .filter(Boolean)
    }
  } catch {
    // ignore and use csv fallback
  }

  return raw
    .split(',')
    .map((entry) => entry.trim())
    .filter(Boolean)
}

/**
 * Resolves a nested value by dot-path (e.g. "realm_access.roles").
 */
export function getByPath(input: unknown, path: string): unknown {
  if (!path) {
    return undefined
  }

  let current: unknown = input
  for (const segment of path.split('.').filter(Boolean)) {
    if (typeof current !== 'object' || current === null || !(segment in current)) {
      return undefined
    }
    current = (current as Record<string, unknown>)[segment]
  }

  return current
}
