"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setup = void 0;
const express_1 = __importDefault(require("express"));
const path_1 = require("path");
const cors_1 = __importDefault(require("cors"));
const http_terminator_1 = require("http-terminator");
const torrent_client_1 = require("./services/torrent-client");
const config_1 = require("./config");
const logging_1 = require("./helpers/logging");
const api_1 = require("./api");
require("express-async-errors");
function createApp(config, logger) {
    logger.info(`Starting app in ${config.environment} environment`);
    const app = express_1.default();
    app.use(cors_1.default());
    app.use(express_1.default.json());
    if (config.trustProxy) {
        logger.info('Enabling proxy support');
        app.set('trust proxy', true);
    }
    return app;
}
async function setup(options) {
    const { configFile } = options || {};
    const config = await config_1.readConfig(configFile);
    const logger = logging_1.createLogger(config);
    const app = createApp(config, logger);
    const client = await torrent_client_1.TorrentClient.create({
        logger,
        ...config.torrents,
    });
    const globals = {
        config,
        logger,
    };
    app.use(api_1.getApiRouter(globals, client));
    if (config.security.frontendEnabled) {
        logger.info('Serving frontend files');
        app.use(express_1.default.static(config_1.frontendBuildPath));
        app.use((_req, res) => {
            res.sendFile(path_1.join(config_1.frontendBuildPath, 'index.html'));
        });
    }
    const server = app.listen(config.port, config.host, () => {
        logger.info(`Listening on ${config.host}:${config.port}`);
        if (config.environment === 'development') {
            const accessHost = config.host === '0.0.0.0' ? '127.0.0.1' : config.host;
            logger.info(`* Website on http://${accessHost}:${config.port}`);
            logger.info(`* Docs on http://${accessHost}:${config.port}/api-docs`);
        }
    });
    const httpTerminator = http_terminator_1.createHttpTerminator({
        server,
    });
    const shutdown = async (signal) => {
        logger.info(`${signal} signal received, closing server`);
        try {
            await httpTerminator.terminate();
        }
        catch (err) {
            logger.error(`Error while terminating HTTP server: ${err}`);
        }
        try {
            await client.destroy();
        }
        catch (err) {
            logger.error(`Error while terminating torrents client: ${err}`);
        }
        process.exit();
    };
    process.on('SIGTERM', shutdown);
    process.on('SIGINT', shutdown);
}
exports.setup = setup;
