import http from "http";
import decrypt from "../../functions/dsql/decrypt";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../../utils/backend/parseCookies";

type Param = {
    request?: http.IncomingMessage;
    cookieString?: string;
    encryptionKey: string;
    encryptionSalt: string;
    database: string;
};

type Return = {
    key: string | undefined;
    csrf: string | undefined;
};

/**
 * Get just the access token for user
 * ==============================================================================
 * @description This Function takes in a request object and returns a user token
 * string and csrf token string
 */
export default function getToken({
    request,
    encryptionKey,
    encryptionSalt,
    cookieString,
}: Param): Return {
    try {
        /**
         * Grab the payload
         *
         * @description Grab the payload
         */
        const cookies = parseCookies({ request, cookieString });
        const keynames = getAuthCookieNames();
        const authKeyName = keynames.keyCookieName;
        const csrfName = keynames.csrfCookieName;

        const key = cookies[authKeyName];
        const csrf = cookies[csrfName];

        /**
         * Grab the payload
         *
         * @description Grab the payload
         */
        let userPayload = decrypt({
            encryptedString: key,
            encryptionKey,
            encryptionSalt,
        });

        /**
         * Grab the payload
         *
         * @description Grab the payload
         */
        if (!userPayload) {
            return { key: undefined, csrf: undefined };
        }

        /**
         * Grab the payload
         *
         * @description Grab the payload
         */
        let userObject = JSON.parse(userPayload);

        if (!userObject.csrf_k) {
            return { key: undefined, csrf: undefined };
        }

        /**
         * Return User Object
         *
         * @description Return User Object
         */
        return { key, csrf };
    } catch (error) {
        /**
         * Return User Object
         *
         * @description Return User Object
         */
        return {
            key: undefined,
            csrf: undefined,
        };
    }
}
