// https://hexdocs.pm/phoenix/asset_management.html#esbuild-plugins
// https://github.com/woutdp/live_svelte/blob/master/lib/mix/tasks/configure_esbuild.ex

const esbuild = require("esbuild");
const sveltePlugin = require("esbuild-svelte");
const importGlobPlugin = require("esbuild-plugin-import-glob").default;
const sveltePreprocess = require("svelte-preprocess");
const { replace } = require("esbuild-plugin-replace");

const args = process.argv.slice(2);
const watch = args.includes("--watch");
const deploy = args.includes("--deploy");

let optsClient = {
  entryPoints: ["js/app.js"],
  bundle: true,
  minify: deploy,
  target: "es2020",
  conditions: ["svelte", "browser"],
  outdir: "../priv/static/assets",
  logLevel: "info",
  sourcemap: watch ? "inline" : false,
  watch,
  tsconfig: "./tsconfig.json",
  plugins: [
    importGlobPlugin(),
    sveltePlugin({
      preprocess: sveltePreprocess(),
      compilerOptions: { dev: !deploy, hydratable: true, css: "injected" },
    }),
    replace({
      __SENTRY_KEY__: process.env.SENTRY_KEY ?? "",
      __OPENREPLAY_KEY__: process.env.OPENREPLAY_KEY ?? "",
    }),
  ],
};

let optsServer = {
  entryPoints: ["js/server.js"],
  platform: "node",
  bundle: true,
  minify: false,
  target: "node19.6.1",
  conditions: ["svelte"],
  outdir: "../priv/svelte",
  logLevel: "info",
  sourcemap: watch ? "inline" : false,
  watch,
  tsconfig: "./tsconfig.json",
  plugins: [
    importGlobPlugin(),
    sveltePlugin({
      preprocess: sveltePreprocess(),
      compilerOptions: { dev: !deploy, hydratable: true, generate: "ssr" },
    }),
  ],
};

const client = esbuild.build(optsClient);
const server = esbuild.build(optsServer);

if (watch) {
  client.then((_result) => {
    process.stdin.on("close", () => process.exit(0));
    process.stdin.resume();
  });

  server.then((_result) => {
    process.stdin.on("close", () => process.exit(0));
    process.stdin.resume();
  });
}
