import path, { resolve } from "node:path";
import URL from "node:url";
import { build } from "unbuild";
import scss from "rollup-plugin-scss";

export async function buildOne(
  dir: string,
  isDev: boolean = false,
  type?: "stub" | "watch"
) {
  const rootDir = resolve("packages/" + dir);
  const pkgInfo = await import(
    URL.pathToFileURL(path.resolve(rootDir, "package.json")).href
  );
  const alias = { [pkgInfo.name]: path.resolve(rootDir, "./src") };

  return build(rootDir, false, {
    stub: type === "stub",
    watch: type === "watch",
    rootDir: rootDir,
    entries: ["src/index.ts"],
    declaration: true,
    replace: {
      __DEV__: `${isDev}`,
      __PROD__: `${!isDev}`,
    },
    alias,
    hooks: {
      "rollup:options"(ctx, options) {
        options.plugins.push(scss({ fileName: "style.css" }));
      },
    },
    rollup: {
      emitCJS: !isDev,
      output: {
        exports: "named",
      },
    },
  });
}