// @ts-ignore -- generated package
import "src/utils/environment";
import * as sapper from "@sapper/server"; // eslint-disable-line import/no-unresolved
import compression from "compression";
import express, { Express } from "express";
import session from "cookie-session";
// @ts-ignore -- doesn't package its own types until 1.0.0-next.6
import sirv from "sirv";
import { createConnection, getConnectionOptions } from "typeorm";
import { DB_ENTITIES } from "@shared/db/entities";
import { logger } from "./utils/logging";
import { AppSession } from "./utils/session";

const PORT = process.env.PORT; // eslint-disable-line prefer-destructuring
// @ts-ignore -- creates a warning after `rollup-plugin-replace` (set up in `rollup.config.js`)
// replaces `process.env.NODE_ENV` with `"production"` during `prod`
const dev = process.env.NODE_ENV === "development";

logger.info("Staring webserver to port %s", PORT);

const key = process.env.WEB_COOKIE_KEY;

if (!key) {
    logger.error("WEB_COOKIE_KEY is not set, cannot run!");
    process.exit();
}

const createSapperServer = async (): Promise<Express> => {
    await createConnection({
        ...await getConnectionOptions(),
        entities: DB_ENTITIES,
    });

    const app = express();

    app.enable("trust proxy");
    app.use(express.json());
    app.use(
        session({
            secret: key,
            name: "session",
            secure: !dev,
        }),
        compression({ threshold: 0 }),
        sirv("static", { dev }),
        sapper.middleware({
            session: (req): AppSession => ({
            }),
        }),
    );

    return app;
};

createSapperServer().then((app) => {
	app.listen(PORT, (err?: any): void => { // eslint-disable-line
        if (err) logger.error("Error on webserver: %s", err);
    });
});

export { sapper };
