import { nodeResolve } from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import commonjs from "@rollup/plugin-commonjs";
import auto from "../plugin-auto-install.js";
import { createRequire } from "module";
import path from "node:path";
import { createExternalHelper } from "../externalHelper.js";
const require = createRequire(import.meta.url);
const packageJson = require("./package.json");

// package to force external
const externalPath = [
  "react",
  "react-dom",
  "@qorebase/app-component",
  "@emotion/react",
  "lodash",
];

// bundle package ignoring its dependencies
const bundlePath = [
  "@qorebase/qore-apps",
  "@qorebase/app-runtime",
  path.resolve("/packages/runtime"),
];

// bundle package with its dependencies
const bundlePackage = [];

const filename = packageJson.module.slice(
  "lib/".length,
  packageJson.module.indexOf(".")
);

/**
 * @type {import('rollup').RollupOptions}
 */
const rollupOptions = {
  input: `src/${filename}.tsx`,
  output: {
    file: `lib/${filename}.js`,
    format: "esm",
  },
  treeshake: {
    moduleSideEffects: false,
  },
  external: createExternalHelper({
    configPath: import.meta.url,
    externalPath,
    bundlePath,
    bundlePackage,
  }),
  plugins: [
    // TODO: this breaks nx cache when enabled
    ...(process.env.PERSIST_AUTO_INSTALL === "true"
      ? [
          auto({
            manager: "yarn",
            ignore: [
              "@qorebase/qore-apps",
              "@qorebase/app-component",
              "@qorebase/app-runtime",
            ],
          }),
        ]
      : []),
    commonjs(),
    nodeResolve({
      browser: true,
    }),
    typescript(),
  ],
};

export default rollupOptions;
