import { defineConfig } from "tsup";
import { globSync } from "glob";

// Exclude any pre-existing .d.ts files; only process .ts source files.
const generatedFiles = globSync("typescript/generated/**/*.ts", {
  ignore: ["**/*.d.ts"],
});

// Create entry points for each generated file
const generatedEntries = generatedFiles.reduce(
  (acc, file) => {
    // Convert path like "typescript/generated/v1beta1/model/ModelSchema.ts"
    // to entry name like "constructs/v1beta1/model/ModelSchema"
    const entryName = file
      .replace("typescript/", "")
      .replace("generated", "constructs")
      .replace(/\.ts$/, "");
    acc[entryName] = file;
    return acc;
  },
  {} as Record<string, string>,
);

const sharedOptions = {
  format: ["cjs", "esm"] as const,
  external: ["react", "react-dom", "react-redux", "@reduxjs/toolkit"],
  splitting: false,
  sourcemap: false,
  treeshake: true,
  minify: true,
  // clean is handled by the Makefile (rm -rf dist/) before invoking tsup so
  // that both configs can write to dist/ without a parallel-clean race.
  // See build-ts target in Makefile.
  clean: false,
};

export default defineConfig([
  {
    // Main API surface — small files, full DTS via tsup's rollup worker.
    // Keep this set small: the worker processes all entry files in one
    // in-memory TypeScript program; adding large generated constructs here
    // causes ERR_WORKER_OUT_OF_MEMORY on the 7 GB ubuntu-24.04 CI runner.
    ...sharedOptions,
    entry: {
      index: "typescript/index.ts",
      cloudApi: "typescript/rtk/cloud.ts",
      mesheryApi: "typescript/rtk/meshery.ts",
      api: "typescript/rtk/api.ts",
      permissions: "typescript/permissions.ts",
    },
    dts: true,
  },
  {
    // Generated construct schemas — large files (497 K lines total), JS only.
    // DTS for these is emitted by build/generate-schema-dts.js which writes
    // minimal declarations without running the full TypeScript type-checker.
    ...sharedOptions,
    entry: generatedEntries,
    dts: false,
  },
]);
