/*
 * Copyright (C) 2019 StApps
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
import {Logger} from '@openstapps/logger';
import express from 'express';
import http from 'http';
import {configureApp} from './app.js';
import {Elasticsearch} from './storage/elasticsearch/elasticsearch.js';

const app = express();

/**
 * Get port from environment and store in Express.
 */
const port = normalizePort(process.env.PORT || '3000');

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Define server handling for specific events
 */
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(value: string) {
  const portNumber = Number.parseInt(value, 10);

  if (Number.isNaN(portNumber)) {
    // named pipe
    return value;
  }

  if (portNumber >= 0) {
    // port number
    return portNumber;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */
async function onError(error: {code: string; syscall: string}) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES': {
      await Logger.error(`${bind} requires elevated privileges`);
      process.exit(1);
      break;
    }
    case 'EADDRINUSE': {
      await Logger.error(`${bind} is already in use`);
      process.exit(1);
      break;
    }
    default: {
      throw error;
    }
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */
function onListening() {
  const addr = server.address();

  if (addr === null) {
    void Logger.error(`Failed to start binding`);
  } else {
    const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
    Logger.ok(`Listening on ${bind}`);
  }
}

configureApp(app, {elasticsearch: Elasticsearch})
  .then(() => {
    Logger.ok('Successfully configured express server');
    // After app setup listen on provided port, on all network interfaces
    server.listen(port);
  })
  // eslint-disable-next-line unicorn/prefer-top-level-await
  .catch(error => {
    throw error;
  });
