const {
  NativeScriptPreviewWebpackPlugin,
} = require("./dist/NativeScriptPreviewWebpackPlugin");

/**
 * @param {typeof import("@nativescript/webpack")} webpack
 */
module.exports = (webpack) => {
  // same API as the user configs
  // for example make changes to the internal config with webpack-chain
  webpack.chainWebpack((config, env) => {
    if (env.preview) {
      config
        .plugin("NativeScriptPreviewWebpackPlugin")
        .use(NativeScriptPreviewWebpackPlugin, [
          {
            platform: webpack.Utils.platform.getPlatformName(),
          },
        ]);

      if (config.plugins.has("ForkTsCheckerWebpackPlugin")) {
        config.plugins.delete("ForkTsCheckerWebpackPlugin");

        if (
          config.module.rules.has("ts") &&
          config.module.rule("ts").uses.has("ts-loader")
        )
          config.module
            .rule("ts")
            .use("ts-loader")
            .tap((options) => {
              if (options && options[0] && "transpileOnly" in options[0]) {
                // make sure we typecheck since we removed the ForkTsChecker...
                options[0].transpileOnly = false;
              }
              return options;
            });
      }
    }
  });
};
