import * as esbuild from 'esbuild';
import path from 'path';
import { fileURLToPath } from 'url';

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

async function build() {
  try {
    await esbuild.build({
      entryPoints: ['./server.ts'],
      bundle: true,
      platform: 'node',
      target: 'node20',
      format: 'esm',
      outfile: 'dist/server.js',
      sourcemap: true,
      minify: process.env.NODE_ENV === 'production',
      
      // Handle TypeScript path aliases by bundling app code
      alias: {
        '~': path.resolve(__dirname, '../app'),
        '~/database': path.resolve(__dirname, '../database'),
      },
      
      // External dependencies (don't bundle node_modules)
      // But DO bundle our application code (database, app modules)
      external: [
        'express',
        'compression',
        'morgan',
        'vite',
        'socket.io',
        'drizzle-orm',
        'postgres',
        '@clerk/*',
        '@react-router/*',
        '../build/server/index.js', // Production build reference (relative to dist/)
      ],
      
      // Keep import.meta.url working
      // Note: path, fileURLToPath are imported in source, so we don't duplicate them here
      banner: {
        js: `
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
        `.trim()
      }
    });
    
    console.log('✅ Server build complete');
  } catch (error) {
    console.error('❌ Build failed:', error);
    process.exit(1);
  }
}

build();
