import { parseJsonOrYaml } from "@scalar/oas-utils/helpers";
import { isConfigurationWithSources, apiReferenceConfigurationWithSourceSchema } from "@scalar/types/api-reference";
import GitHubSlugger from "github-slugger";
const normalizeConfigurations = (configuration) => {
  const slugger = new GitHubSlugger();
  const normalized = {};
  if (!configuration) {
    return normalized;
  }
  const configList = Array.isArray(configuration) ? configuration : [configuration];
  configList.flatMap((c) => {
    if (isConfigurationWithSources(c)) {
      const { sources: configSources, ...rest } = c;
      return configSources?.map((source) => ({ ...rest, ...source })) ?? [];
    }
    return [c];
  }).map((source) => {
    const validated = apiReferenceConfigurationWithSourceSchema.safeParse(source);
    return validated.success ? validated.data : null;
  }).filter((c) => !!c && (!!c.url || !!c.content)).map((source, index) => addSlugAndTitle(source, index, slugger)).forEach((c) => {
    const { url, content, ...config } = c;
    normalized[c.slug] = {
      config,
      title: c.title,
      slug: c.slug,
      default: !!c?.default,
      source: content ? { content: normalizeContent(content) ?? {} } : { url }
    };
  });
  return normalized;
};
const normalizeContent = (content) => {
  if (!content) {
    return null;
  }
  if (typeof content === "function") {
    return normalizeContent(content());
  }
  if (typeof content === "string") {
    return parseJsonOrYaml(content);
  }
  return content;
};
const addSlugAndTitle = (source, index = 0, slugger) => {
  if (source.title) {
    return {
      ...source,
      slug: source.slug || slugger.slug(source.title),
      title: source.title
    };
  }
  if (source.slug) {
    return {
      ...source,
      slug: slugger.slug(source.slug),
      title: source.slug
    };
  }
  return {
    ...source,
    slug: `api-${index + 1}`,
    title: `API #${index + 1}`
  };
};
export {
  addSlugAndTitle,
  normalizeConfigurations,
  normalizeContent
};
