import {readFileSync} from "node:fs";
import {builtinModules} from "node:module";
import {resolve, join} from "node:path";

import nodeResolve from "@rollup/plugin-node-resolve";
import babelPlugin from "@rollup/plugin-babel";
import deletePlugin from "rollup-plugin-delete";


/**
 * Create a base rollup config
 * @param {Record<string,any>} pkg Imported package.json
 * @param {string[]} external Imported package.json
 * @returns {import('rollup').RollupOptions}
 */
export function createConfig({ pkg, external = [] }) {
  const commonOpts = {
    extensions: ['.js', '.mjs', '.jsx', '.ts', '.tsx'],
    exclude: 'node_modules/**',
  };

  return {
    input: 'src/index.ts',
    external: Object.keys(pkg.dependencies || {})
        .concat(Object.keys(pkg.peerDependencies || {}))
        .concat(builtinModules)
        .concat(external),
    onwarn: (warning) => {
      throw Object.assign(new Error(), warning);
    },
    strictDeprecations: true,
    output: [
      // TODO: cjs output not supported for now
      // {
      //   format: 'cjs',
      //   file: pkg.main,
      //   exports: 'named',
      //   footer: 'module.exports = Object.assign(exports.default, exports);',
      //   sourcemap: true
      // },
      {
        format: 'es',
        file: pkg.module,
        plugins: [emitModulePackageFile()],
        sourcemap: true
      }
    ],
    plugins: [
      deletePlugin({
        targets: join('./dist','*'),
        runOnce: true,
      }),
      nodeResolve({
        ...commonOpts,
        browser: true,
      }),
      babelPlugin({
        ...commonOpts,
        babelHelpers: "bundled",
      }),
    ]
  };
}

export function emitModulePackageFile() {
  return {
    name: 'emit-module-package-file',
    generateBundle() {
      this.emitFile({
        type: 'asset',
        fileName: 'package.json',
        source: `{"type":"module"}`
      });
    }
  };
}

export default createConfig({
  pkg: JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
});
