// @ts-check

const { createServer } = require("http");
const { parse } = require("url");
const fs = require("fs");
const path = require("path");
require("dotenv").config({ path: path.join(__dirname, ".env") });

const next = require("next");

const production = process.env.NODE_ENV == "production";
const dev = process.env.NODE_ENV !== "production";
const isLocal = process.env.NEXT_PUBLIC_DSQL_LOCAL || null;
const hostname = "localhost";
const port = process.env.WEB_PORT || 7070;

// @ts-ignore
const app = next({
    dev,
    hostname,
    port,
});

const handle = app.getRequestHandler();

const serverSocket = require("./utils/socket");

app.prepare()
    .then(() => {
        const server = createServer(async (req, res) => {
            try {
                const parsedUrl = parse(req.url || "", true);
                const { pathname, query } = parsedUrl;

                await handle(req, res, parsedUrl);
            } catch (err) {
                console.error("Error occurred handling", req.url, err);
                res.statusCode = 500;
                res.end("internal server error");
            }
        });

        server.on("error", (err) => {
            console.error("⚠️ SERVER ERROR =>", err.message);
        });

        server.listen(port, () => {
            console.log(`> Ready on http://${hostname}:${port}`);
        });

        serverSocket(server);
    })
    .catch((error) => {
        console.log(error);
    });

/**
 * Setup needed directories
 */
if (!fs.existsSync("./.tmp")) {
    fs.mkdirSync("./.tmp", { recursive: true });
}

// const MAX_LOG_FILE_LENGTH = 2000;

// const originalConsoleLog = console.log;
// console.log = function (...args) {
//     const logMessage = args
//         .map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : arg))
//         .join(" ");
//     fs.appendFileSync("./log.log", logMessage + "\n", "utf8");
//     originalConsoleLog.apply(console, args);
// };

/**
 * # Start Cron Jobs
 */
// require("./utils/cron")();
