import http from "http";
import decrypt from "../package-shared/functions/dsql/decrypt";
import { DATASQUIREL_LoggedInUser } from "../package-shared/types";

type Param = {
    token: string;
    encryptionKey: string;
    encryptionSalt: string;
    level?: ("deep" | "normal") | null;
    database: string;
};

/**
 * Validate Token
 * ======================================
 * @description This Function takes in a encrypted token and returns a user object
 */
export default function validateToken({
    token,
    encryptionKey,
    encryptionSalt,
}: Param): DATASQUIREL_LoggedInUser | null {
    try {
        /**
         * Grab the payload
         *
         * @description Grab the payload
         */
        const key = token;

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

        /**
         * Grab the payload
         *
         * @description Grab the payload
         */
        if (!userPayload) {
            return null;
        }

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

        if (!userObject.csrf_k) {
            return null;
        }

        /**
         * Return User Object
         *
         * @description Return User Object
         */
        return userObject;
    } catch (error) {
        /**
         * Return User Object
         *
         * @description Return User Object
         */
        return null;
    }
}