import { build } from 'esbuild';
import fs from 'node:fs';
import path from 'node:path';

const projectRoot = process.cwd();
const pkgPath = path.join(projectRoot, 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

const dependencies = Object.keys(pkg.dependencies ?? {});
const optionalDependencies = Object.keys(pkg.optionalDependencies ?? {});
const peerDependencies = Object.keys(pkg.peerDependencies ?? {});

const externals = Array.from(
  new Set([
    ...dependencies,
    ...optionalDependencies,
    ...peerDependencies,
    // also keep these as runtime externals
    'sqlite3',
  ]),
);

await build({
  entryPoints: ['api/server.ts'],
  outfile: 'dist/api/server.js',
  bundle: true,
  platform: 'node',
  format: 'esm',
  target: ['node20'],
  sourcemap: true,
  logLevel: 'info',
  external: externals,
});

console.log('Built backend -> dist/api/server.js');
