// @ts-check

const { IncomingMessage } = require("http");
const parseCookies = require("../../utils/backend/parseCookies");
const decrypt = require("../dsql/decrypt");
const getAuthCookieNames = require("./cookies/get-auth-cookie-names");

/**
 * @async
 * @param {IncomingMessage} req - https request object
 *
 * @returns {Promise<({ email: string, password: string, authKey: string, logged_in_status: boolean, date: number } | null)>}
 */
module.exports = async function (req) {
    const { keyCookieName, csrfCookieName } = getAuthCookieNames();
    const suKeyName = `${keyCookieName}_su`;

    const cookies = parseCookies({ request: req });
    if (!cookies?.[suKeyName]) {
        return null;
    }

    /** ********************* Grab the payload */
    let userPayload = decrypt({
        encryptedString: cookies[suKeyName],
    });

    /** ********************* Return if no payload */
    if (!userPayload) return null;

    /** ********************* Parse the payload */
    let userObject = JSON.parse(userPayload);

    if (userObject.password !== process.env.DSQL_USER_KEY) return null;
    if (userObject.authKey !== process.env.DSQL_SPECIAL_KEY) return null;

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

    /** ********************* return user object */
    return userObject;
};
