import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";

const isMinifiedBuild = process.env.ORG_CONTEXT_CHART_MINIFY === "true";
const buildId = process.env.ORG_CONTEXT_CHART_BUILD_ID ?? createBuildId();
const fileSuffix = isMinifiedBuild ? ".min" : "";
const fileBaseName = `boc-${buildId}${fileSuffix}`;

function createBuildId() {
  const now = new Date();
  const year = String(now.getFullYear()).slice(-2);
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const random = String(Math.floor(Math.random() * 10000)).padStart(4, "0");
  return `${year}${month}${random}`;
}

export default defineConfig({
  build: {
    emptyOutDir: !isMinifiedBuild,
    lib: {
      entry: fileURLToPath(
        new URL("./src/sdk/org-context-chart/index.ts", import.meta.url),
      ),
      fileName: (format) =>
        format === "es" ? `${fileBaseName}.js` : `${fileBaseName}.umd.cjs`,
      formats: ["es", "umd"],
      name: "BaronOrgContextChart",
    },
    minify: isMinifiedBuild,
    outDir: "dist/org-context-chart",
    sourcemap: true,
  },
});
