import {
  AngularNodeAppEngine,
  createNodeRequestHandler,
  isMainModule,
  writeResponseToNodeResponse,
} from '@angular/ssr/node';
import express from 'express';
import {createProxyMiddleware} from 'http-proxy-middleware';
import {join} from 'node:path';

const browserDistFolder = join(import.meta.dirname, '../browser');

const app = express();
const angularApp = new AngularNodeAppEngine();

app.use(
  '/api',
  createProxyMiddleware({
    target: 'http://backend:3000', // FIXME: Use environment variable for DEV/PROD backend URL
    changeOrigin: true,
    pathRewrite: (path) => `/api${path}`,
  }),
);

app.use(
  '/auth',
  createProxyMiddleware({
    target: 'http://keycloak:8080', // FIXME: Use environment variable for DEV/PROD keycloak URL
    changeOrigin: true,
    pathRewrite: (path) => `/auth${path}`,
  }),
);

app.use(
  express.static(browserDistFolder, {
    maxAge: '1y',
    index: false,
    redirect: false,
  }),
);

app.use((req, res, next) => {
  angularApp
    .handle(req)
    .then((response) =>
      response ? writeResponseToNodeResponse(response, res) : next(),
    )
    .catch(next);
});

if (isMainModule(import.meta.url)) {
  const port = process.env['PORT'] || 4000;
  app.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

export const reqHandler = createNodeRequestHandler(app);
