import 'zone.js/dist/zone-node';

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import * as cors from 'cors';
import { existsSync } from 'fs';
import { join } from 'path';

import<% if(standalone) { %> bootstrap <% } else { %> { AppServerModule } <% } %>from './bootstrap.server';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const browserBundles = join(process.cwd(), 'dist/apps/<%= appName %>/browser');

  server.use(cors());
  const indexHtml = existsSync(join(browserBundles, 'index.original.html'))
    ? 'index.original.html'
    : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
  server.engine(
    'html',
    ngExpressEngine({
      <% if(standalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule,<% } %>
    })
  );

  server.set('view engine', 'html');
  server.set('views', browserBundles);

  // Serve static files from /browser
  server.get(
    '*.*',
    express.static(browserBundles, {
      maxAge: '1y',
    })
  );

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    // keep it async to avoid blocking the server thread

    res.render(indexHtml, {
      providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
      req,
    });
  });

  return server;
}

function run(): void {
  const port = process.env['PORT'] || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

run();

<% if(standalone) { %>export default bootstrap;<% } else { %>export * from './bootstrap.server';<% } %>
