import fs from "fs";
import path from "path";

export default function getAvatar(
    userId: string,
    avatar: string | null | undefined,
    fallback: string
): string {
    const rootPath = process.env.PUBLIC_AVATAR_URL;
    if (userId == null) return fallback;
    if (avatar == undefined || avatar == null || avatar === "") return fallback;

    const rootDir =
        process.env.NODE_ENV !== "production"
            ? process.env.GET_AVATAR_USERS_FILES_ROOT_DEV
            : process.env.GET_AVATAR_USERS_FILES_ROOT_PRO;

    const uploadPath = path.join(__dirname, rootDir + userId);

    const filePath = path.join(uploadPath, avatar);

    if (!fs.existsSync(filePath)) {
        return fallback;
    }

    return avatar ? rootPath + userId + "/" + avatar : "";
}
