import esbuild from 'esbuild'
import path from 'path'
import { existsSync } from 'fs'
import { dirname } from 'path'
import { fileURLToPath } from 'url'

const __dirname = dirname(fileURLToPath(import.meta.url))

export default async function build() {
  const esmLoaderSrc = path.join(__dirname, '..', 'runtimes', 'nodejs20', 'esm-loader.ts')
  const cjsLoaderSrc = path.join(__dirname, '..', 'runtimes', 'nodejs20', 'cjs-loader.ts')

  const outdir = path.join(__dirname, 'dist')
  const esmLoaderDst = path.join(outdir, 'esm-loader.mjs')
  const cjsLoaderDst = path.join(outdir, 'cjs-loader.js')

  if (existsSync(esmLoaderDst) && existsSync(cjsLoaderDst)) {
    return
  }

  // https://github.com/evanw/esbuild/issues/946#issuecomment-814703190
  const banner = {
    js: [
      `import { createRequire as topLevelCreateRequire } from 'module'`,
      `const require = topLevelCreateRequire(import.meta.url)`
    ].join('\n')
  }

  await Promise.all([
    esbuild.build({
      absWorkingDir: __dirname,
      entryPoints: [esmLoaderSrc],
      external: ['lz4-wasm-nodejs', 'esbuild', '@aws-sdk/credential-providers'], // provided by runtime
      outdir: outdir,
      format: 'esm',
      bundle: true,
      splitting: false,
      minify: true,
      write: true,
      sourcemap: true,
      sourcesContent: false,
      platform: 'node',
      target: 'node20.11.0',
      banner,
      outExtension: {
        '.js': '.mjs'
      }
    }),
    esbuild.build({
      absWorkingDir: __dirname,
      entryPoints: [cjsLoaderSrc],
      external: ['lz4-wasm-nodejs', 'esbuild', '@aws-sdk/credential-providers'], // provided by runtime
      outdir,
      format: 'cjs',
      bundle: true,
      splitting: false,
      minify: true,
      write: true,
      sourcemap: true,
      sourcesContent: false,
      platform: 'node',
      target: 'node20.11.0'
    })
  ])
}
