const path = require('path')
const { createRequire } = require('module')
const { getDefaultConfig } = require('expo/metro-config')
const { withNativeWind } = require('nativewind/metro')

const projectRoot = __dirname
const workspaceRoot = path.resolve(projectRoot, '../..')
const appRequire = createRequire(path.join(projectRoot, 'package.json'))
const reactEntry = appRequire.resolve('react')
const reactJsxRuntime = appRequire.resolve('react/jsx-runtime')
const reactJsxDevRuntime = appRequire.resolve('react/jsx-dev-runtime')
const reactRoot = path.dirname(appRequire.resolve('react/package.json'))
const reactNativeRoot = path.dirname(appRequire.resolve('react-native/package.json'))

const config = getDefaultConfig(projectRoot)

// Monorepo: Metro muss die Workspace-Pakete finden
config.watchFolders = [workspaceRoot]
config.resolver.nodeModulesPaths = [
  path.resolve(projectRoot, 'node_modules'),
  path.resolve(workspaceRoot, 'node_modules'),
]
config.resolver.extraNodeModules = {
  ...(config.resolver.extraNodeModules || {}),
  react: reactRoot,
  'react-native': reactNativeRoot,
}
const originalResolveRequest = config.resolver.resolveRequest
config.resolver.resolveRequest = (context, moduleName, platform) => {
  if (moduleName === 'react') {
    return { type: 'sourceFile', filePath: reactEntry }
  }
  if (moduleName === 'react/jsx-runtime') {
    return { type: 'sourceFile', filePath: reactJsxRuntime }
  }
  if (moduleName === 'react/jsx-dev-runtime') {
    return { type: 'sourceFile', filePath: reactJsxDevRuntime }
  }

  const resolver = originalResolveRequest ?? context.resolveRequest
  return resolver(context, moduleName, platform)
}

module.exports = withNativeWind(config, { input: './global.css' })
