/**
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE-MIT file in the root directory of this source tree.
 */

const path = require('path');
const { mergeConfig, getDefaultConfig } = require('@react-native/metro-config');
const { createHarmonyMetroConfig } = require('@react-native-oh/react-native-harmony/metro.config');

const harmonyMetroConfig = createHarmonyMetroConfig({
  reactNativeHarmonyPackageName: '@react-native-oh/react-native-harmony',
});

const tabsScreensWebStubByRelativeImport = {
  './TabsScreen': 'TabsScreen.web.tsx',
  './TabsHost': 'TabsHost.web.tsx',
};

const upstreamHarmonyResolveRequest = harmonyMetroConfig.resolver.resolveRequest;
harmonyMetroConfig.resolver.resolveRequest = (ctx, moduleName, platform) => {
  if (platform === 'harmony' && ctx.originModulePath) {
    const origin = ctx.originModulePath.replace(/\\/g, '/');
    const stubFile = tabsScreensWebStubByRelativeImport[moduleName];
    if (
      stubFile &&
      origin.includes('react-native-screens/src/components/tabs/')
    ) {
      return {
        type: 'sourceFile',
        filePath: path.join(path.dirname(ctx.originModulePath), stubFile),
      };
    }
  }
  return upstreamHarmonyResolveRequest(ctx, moduleName, platform);
};

/**
 * @type {import("metro-config").ConfigT}
 */
const config = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: true,
      },
    }),
  },
};

module.exports = mergeConfig(getDefaultConfig(__dirname), harmonyMetroConfig, config);