import type { RichTextAdapter } from 'payload'

import { genImportMapIterateFields } from 'payload'

import type { ResolvedServerFeatureMap } from '../features/typesServer.js'

export const getGenerateImportMap =
  (args: { resolvedFeatureMap: ResolvedServerFeatureMap }): RichTextAdapter['generateImportMap'] =>
  ({ addToImportMap, baseDir, config, importMap, imports }) => {
    addToImportMap('@payloadcms/richtext-lexical/client#RichTextCell')
    addToImportMap('@payloadcms/richtext-lexical/client#RichTextField')
    addToImportMap('@payloadcms/richtext-lexical/generateComponentMap#getGenerateComponentMap')

    // iterate just through args.resolvedFeatureMap.values()
    for (const resolvedFeature of args.resolvedFeatureMap.values()) {
      if ('componentImports' in resolvedFeature) {
        if (typeof resolvedFeature.componentImports === 'function') {
          resolvedFeature.componentImports({
            addToImportMap,
            baseDir,
            config,
            importMap,
            imports,
          })
        } else if (resolvedFeature.componentImports?.length) {
          resolvedFeature.componentImports.forEach((component) => {
            addToImportMap(component)
          })
        }
      }

      const ClientComponent = resolvedFeature.ClientFeature
      if (ClientComponent) {
        addToImportMap(ClientComponent)
      }

      /*
        Now run for all possible sub-fields
       */
      if (resolvedFeature.nodes?.length) {
        for (const node of resolvedFeature.nodes) {
          if (typeof node?.getSubFields !== 'function') {
            continue
          }
          const subFields = node.getSubFields({})
          if (subFields?.length) {
            genImportMapIterateFields({
              addToImportMap,
              baseDir,
              config,
              fields: subFields,
              importMap,
              imports,
            })
          }
        }
      }
    }
  }
