import { IncomingMessage } from "http";

/**
 * Parse request cookies
 * ===================================================
 *
 * @description This function takes in a request object and
 * returns the cookies as a JS object
 */
export default function parseCookies({
    request,
    cookieString,
}: {
    request?: IncomingMessage & { [s: string]: any };
    cookieString?: string;
}): { [s: string]: string } {
    try {
        /** @type {string | undefined} */
        const cookieStr = request
            ? request.headers.cookie
            : cookieString
            ? cookieString
            : undefined;

        if (!cookieStr) return {};

        if (!cookieStr || typeof cookieStr !== "string") {
            return {};
        }

        const cookieSplitArray: string[] = cookieStr.split(";");

        let cookieObject: { [k: string]: string } = {};

        cookieSplitArray.forEach((keyValueString) => {
            const [key, value] = keyValueString.split("=");
            if (key && typeof key == "string") {
                const parsedKey = key.replace(/^ +| +$/, "");
                cookieObject[parsedKey] =
                    value && typeof value == "string"
                        ? value.replace(/^ +| +$/, "")
                        : "";
            }
        });

        return cookieObject;
    } catch (error: any) {
        console.log(`ERROR parsing cookies: ${error.message}`);

        return {};
    }
}