const esbuild = require("esbuild");
const path = require("path");

// colors for console output
const consoleColors = {
  info: "\x1b[34m", // Blue
  success: "\x1b[32m", // Green
  warning: "\x1b[33m", // Yellow
  error: "\x1b[31m", // Red
  reset: "\x1b[0m", // Reset
};

const createDefinitions = process => {
  return Object.keys(process.env).reduce((acc, key) => {
    acc[`process.env.${key}`] = JSON.stringify(process.env[key]);
    return acc;
  }, {});
};

const entryPoint = file => path.join(process.cwd(), file);

const build = async config => {
  try {
    console.info(
      `${consoleColors.info}[esbuild]${consoleColors.reset} Building...`
    );
    await esbuild.build(config);
    console.info(
      `${consoleColors.success}[esbuild]${consoleColors.reset} Build successful`
    );
  } catch {
    const errorMessage = `${consoleColors.error}[esbuild]${consoleColors.reset} Build failed`;
    throw new Error(errorMessage);
  }
};

const watch = async config => {
  const ctx = await esbuild.context(config);
  await ctx.watch();
  await ctx.serve({
    servedir: config.outdir,
    port: parseInt(process.env.DEVSERVER_PORT || "8000"),
  });
};

module.exports = {
  consoleColors,
  createDefinitions,
  entryPoint,
  build,
  watch,
};
