import http from "http";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../../utils/backend/parseCookies";
import decrypt from "../../functions/dsql/decrypt";
import EJSON from "../../utils/ejson";
import { SendOneTimeCodeEmailResponse } from "../../types";

type Param = {
    request?: http.IncomingMessage & { [s: string]: any };
    cookieString?: string;
    email?: string;
};

/**
 * # Verify the temp email code sent to the user's email address
 */
export default async function validateTempEmailCode({
    request,
    email,
    cookieString,
}: Param): Promise<SendOneTimeCodeEmailResponse | null> {
    try {
        const keyNames = getAuthCookieNames();
        const oneTimeCodeCookieName = keyNames.oneTimeCodeName;

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

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

        const payload = EJSON.parse(encryptedPayload) as
            | SendOneTimeCodeEmailResponse
            | undefined;

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

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

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