import { build } from 'esbuild';
import { resolve, dirname } from 'path';
import { mkdirSync } from 'fs';
import { fileURLToPath } from 'url';

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

const entryPoints = [
    resolve(__dirname, 'src/index.ts'),
    resolve(__dirname, 'src/server.ts')
];

try {
    mkdirSync(resolve(__dirname, 'dist'), { recursive: true });
} catch (_e) {
    // Ignore folder creation errors if it already exists
}

console.log(`Building entry points...`);

build({
    entryPoints: entryPoints,
    bundle: true,
    platform: 'node',
    target: 'node18',
    outdir: resolve(__dirname, 'dist'),
    format: 'esm',
    jsx: 'automatic',
    loader: {
        '.tsx': 'tsx',
        '.ts': 'ts',
        '.js': 'js',
    },
    external: ["@react-pdf/renderer", "react", "react-dom", "jsdom", "jsdom/*", "jquery", "jquery/*", "canvas", "fs", "path", "os", "http", "https", "zlib", "stream", "util", "url", "net", "tls", "crypto"],
    plugins: [{
        name: 'mock-canvas',
        setup(build) {
            build.onResolve({ filter: /^canvas/ }, args => ({ path: args.path, namespace: 'mock-canvas' }));
            build.onLoad({ filter: /.*/, namespace: 'mock-canvas' }, () => ({ contents: 'export default {};', loader: 'js' }));
        }
    }, {
        name: 'mock-jsdom',
        setup(build) {
            build.onResolve({ filter: /^jsdom/ }, args => ({ path: args.path, namespace: 'mock-jsdom' }));
            build.onLoad({ filter: /.*/, namespace: 'mock-jsdom' }, () => ({ contents: 'export default {};', loader: 'js' }));
        }
    }]
}).then(() => {
    console.log("Build succeeded!");
}).catch((e) => {
    if (e.errors) {
        console.error("Build failed with errors:");
        e.errors.forEach(err => console.error(`  ${err.text} at ${err.location?.file}:${err.location?.line}`));
    } else {
        console.error("Build failed:", e);
    }
    process.exit(1);
});
