import type { MarkdownDocumentEntry } from '../../components/markdownPreview';

const docsMarkdownModules = import.meta.glob('/docs/**/*.md', {
  query: '?raw',
  import: 'default',
}) as Record<string, () => Promise<string>>;

const featureMarkdownModules = import.meta.glob('../../features/**/*.md', {
  query: '?raw',
  import: 'default',
}) as Record<string, () => Promise<string>>;

const DOCS_ENTRY_DEFINITIONS: Array<Pick<MarkdownDocumentEntry, 'path' | 'folder' | 'title'>> = [
  {
    path: '/docs/README.md',
    folder: 'project',
    title: '프로젝트 구조',
  },
];

const FEATURE_ENTRY_PATTERNS = [/\/overview\.md$/i, /\/README\.md$/i];

function createExplicitMarkdownEntries(
  modules: Record<string, () => Promise<string>>,
  entries: Array<Pick<MarkdownDocumentEntry, 'path' | 'folder' | 'title'>>,
): MarkdownDocumentEntry[] {
  return entries
    .filter((entry) => typeof modules[entry.path] === 'function')
    .map((entry, index) => ({
      ...entry,
      load: modules[entry.path],
      order: index,
    }));
}

function createFilteredMarkdownEntries(
  modules: Record<string, () => Promise<string>>,
  includePatterns: RegExp[],
): MarkdownDocumentEntry[] {
  return Object.keys(modules)
    .filter((path) => includePatterns.some((pattern) => pattern.test(path)))
    .sort((left, right) => left.localeCompare(right))
    .map((path, index) => ({
      path,
      load: modules[path],
      order: index,
    }));
}

export const docsMarkdownEntries = createExplicitMarkdownEntries(
  docsMarkdownModules,
  DOCS_ENTRY_DEFINITIONS,
);
export const featureMarkdownEntries = createFilteredMarkdownEntries(
  featureMarkdownModules,
  FEATURE_ENTRY_PATTERNS,
);
