import * as esbuild from 'esbuild';
import { denoPlugins } from '@luca/esbuild-deno-loader';
import { join } from '@std/path';

if (import.meta.main) {
  for (const dirEntry of Deno.readDirSync(
    join(import.meta.dirname ?? '', '../bunny')
  )) {
    if (dirEntry.isFile && dirEntry.name.endsWith('.ts')) {
      const outFilename =
        dirEntry.name.substring(0, dirEntry.name.length - 3) + '.js';

      const res = await esbuild.build({
        plugins: [
          ...denoPlugins({
            loader: 'native',
          }),
        ],
        entryPoints: [
          join(import.meta.dirname ?? '', '../bunny', dirEntry.name),
        ],
        outfile: join(import.meta.dirname ?? '', '../build/bunny', outFilename),
        bundle: true,
        format: 'esm',
      });

      await esbuild.stop();

      if (res.errors.length > 0) {
        console.error(
          `Got errors when trying to bundle ${dirEntry.name}: ${JSON.stringify(
            res.errors
          )}`
        );
      }

      if (res.warnings.length > 0) {
        console.warn(
          `Got warnings when trying to bundle ${
            dirEntry.name
          }: ${JSON.stringify(res.warnings)}`
        );
      }
    }
  }
}