// @ts-check

const fs = require("fs");
const { IncomingMessage } = require("http");

/**
 * # Server Error
 *
 * @param {{
 *  user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *,
 *  message: string,
 *  component?: string,
 *  noMail?: boolean,
 *  req?: import("next").NextApiRequest & IncomingMessage,
 * }} params - user id
 *
 * @returns {Promise<void>}
 */
module.exports = async function serverError({
    user,
    message,
    component,
    noMail,
    req,
}) {
    const date = new Date();

    const reqIp = (() => {
        if (!req) return null;
        try {
            const forwarded = req.headers["x-forwarded-for"];
            const realIp = req.headers["x-real-ip"];
            const cloudflareIp = req.headers["cf-connecting-ip"];

            // Convert forwarded IPs to string and get the first IP if multiple exist
            const forwardedIp = Array.isArray(forwarded)
                ? forwarded[0]
                : forwarded?.split(",")[0];

            const clientIp =
                cloudflareIp ||
                forwardedIp ||
                realIp ||
                req.socket.remoteAddress;
            if (!clientIp) return null;

            return String(clientIp);
        } catch (error) {
            return null;
        }
    })();

    try {
        let log = `🚀 SERVER ERROR ===========================\nError Message: ${message}\nComponent: ${component}`;

        if (user?.id && user?.first_name && user?.last_name && user?.email) {
            log += `\nUser Id: ${user?.id}\nUser Name: ${user?.first_name} ${user?.last_name}\nUser Email: ${user?.email}`;
        }

        if (req?.url) {
            log += `\nURL: ${req.url}`;
        }

        if (req?.body) {
            log += `\nRequest Body: ${JSON.stringify(req.body, null, 4)}`;
        }

        if (reqIp) {
            log += `\nIP: ${reqIp}`;
        }

        log += `\nDate: ${date.toDateString()}`;
        log += "\n========================================";

        if (!fs.existsSync(`./.tmp/error.log`)) {
            fs.writeFileSync(`./.tmp/error.log`, "", "utf-8");
        }

        const initialText = fs.readFileSync(`./.tmp/error.log`, "utf-8");

        fs.writeFileSync(`./.tmp/error.log`, log);
        fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
    } catch (/** @type {any} */ error) {
        console.log("Server Error Reporting Error:", error.message);
    }
};

////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////