// @ts-check

const http = require("http");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const EJSON = require("../package-shared/utils/ejson");

/**
 * Verify the temp email code sent to the user's email address
 * ==============================================================================
 * @async
 *
 * @param {object} params - Single Param object containing params
 * @param {http.IncomingMessage & Object<string, any>} [params.request]
 * @param {string} [params.cookieString]
 * @param {string} [params.email]
 *
 * @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse | null>}
 */
async function validateTempEmailCode({ request, email, cookieString }) {
    try {
        const keyNames = getAuthCookieNames();
        const oneTimeCodeCookieName = keyNames.oneTimeCodeName;

        const cookies = parseCookies({ request, cookieString });
        const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];

        const encryptedPayload = decrypt({
            encryptedString: encryptedOneTimeCode,
        });

        const payload =
            /** @type {import("../package-shared/types").SendOneTimeCodeEmailResponse | undefined} */ (
                EJSON.parse(encryptedPayload)
            );

        if (payload?.email && !email) {
            return payload;
        }

        if (payload?.email && payload.email === email) {
            return payload;
        }

        return null;
    } catch (/** @type {any} */ error) {
        console.log("validateTempEmailCode error:", error.message);
        return null;
    }
}

module.exports = validateTempEmailCode;