#!/usr/bin/env node
"use strict";
/* eslint-disable no-console */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const express_1 = __importDefault(require("express"));
const next_1 = __importDefault(require("next"));
const config_1 = require("next/config");
const middlewares_1 = require("../utils/i18next/middlewares");
const i18n_1 = __importDefault(require("../utils/i18n"));
const next_config_1 = __importDefault(require("../next.config"));
const isDev = process.env.NODE_ENV !== 'production';
config_1.setConfig(next_config_1.default);
const host = process.env.HOST || 'localhost';
const port = Number.parseInt(process.env.PORT, 10) || 8999;
const backend = process.env.BACKEND;
const delay = Number.parseInt(process.env.DELAY, 10);
const server = express_1.default();
exports.server = server;
const app = next_1.default({ dev: isDev, conf: next_config_1.default });
exports.app = app;
const handle = app.getRequestHandler();
async function start() {
    await app.prepare();
    if (backend) {
        const { createProxyMiddleware } = await Promise.resolve().then(() => __importStar(require('http-proxy-middleware')));
        server.use(next_config_1.default.env.API_URL, createProxyMiddleware({ target: backend, changeOrigin: true }));
    }
    else if (isDev) {
        const { default: mock } = await Promise.resolve().then(() => __importStar(require('../utils/mock')));
        server.use(next_config_1.default.env.API_URL, mock({ path: path_1.default.resolve(__dirname, '../mock'), delay: delay ? () => Math.random() * delay : 0 }));
    }
    await i18n_1.default.initPromise;
    server.use(middlewares_1.nextI18NextMiddleware(i18n_1.default));
    server.get(/\.wasm/, (_req, res, next) => {
        res.type('application/wasm');
        next();
    });
    server.get('*', (req, res) => handle(req, res));
    const s = server.listen(port, host, () => {
        var _a;
        (_a = process.send) === null || _a === void 0 ? void 0 : _a.call(process, 'ready');
        console.log(`> Ready on http://${host}:${port}`);
        process.on('SIGINT', () => {
            s.close((err) => {
                if (err) {
                    throw err;
                }
                process.exit(0);
            });
        });
    });
}
if (require.main === module) {
    start();
}
exports.default = start;
