const path = require('path')

/** Sets up Jest configuration for packages that use core-react components */
function coreReactJestConfig(config) {
  const coreReactDeps = '@ckeditor|ckeditor5|es-toolkit'

  const existingIgnorePatterns = config.transformIgnorePatterns || []

  //Add our dependencies to any existing node_modules pattern
  const updatedIgnorePatterns = existingIgnorePatterns.map((pattern) => {
    if (pattern.includes('node_modules/(?!')) {
      return pattern.replace(
        /node_modules\/\(\?\!([^)]*)\)/,
        (match, existingDeps) =>
          `node_modules/(?!(${coreReactDeps}|${existingDeps}))`
      )
    }
    return pattern
  })

  // If no node_modules pattern exists, add our own
  const hasNodeModulesPattern = existingIgnorePatterns.some((pattern) =>
    pattern.includes('node_modules/(?!')
  )

  if (!hasNodeModulesPattern) {
    updatedIgnorePatterns.push(`node_modules/(?!(${coreReactDeps}))`)
  }

  // Helper to resolve mock files
  function resolveMockFile(mockFileName) {
    return path.resolve(__dirname, '.jest', mockFileName)
  }

  return {
    ...config,
    moduleNameMapper: {
      '^ckeditor5$': resolveMockFile('ckeditorMock.js'),
      '^@ckeditor/ckeditor5-react$': resolveMockFile('ckeditorMock.js'),
      '^ckeditor5/translations/(.+)\\.js$': resolveMockFile('fileMock.js'),
      '^es-toolkit/compat$': resolveMockFile('esToolkitMock.js'),
      ...config.moduleNameMapper,
    },
    transform: {
      '\\.svg$': resolveMockFile('svgTransform.js'),
      ...config.transform,
    },
    transformIgnorePatterns: updatedIgnorePatterns,
  }
}

module.exports = { coreReactJestConfig }
