// @ts-check

import fs from "fs";
import { IncomingMessage } from "http";

type Param = {
    user?: {
        id?: number | string;
        first_name?: string;
        last_name?: string;
        email?: string;
    } & any;
    message: string;
    component?: string;
    noMail?: boolean;
    req?: import("next").NextApiRequest & IncomingMessage;
};

/**
 * # Server Error
 */
export default async function serverError({
    user,
    message,
    component,
    noMail,
    req,
}: Param): Promise<void> {
    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: any) {
        console.log("Server Error Reporting Error:", error.message);
    }
}

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