import { getToken } from "next-auth/jwt";
import { readFileSync, existsSync } from "node:fs";
import { join, resolve } from "node:path";

let findGitRoot = (path = __dirname): string | false => {
    if (existsSync(join(path, ".git/HEAD"))) {
        return path;
    } else {
        let parent = resolve(path, "..");
        if (path === parent) {
            return false;
        } else {
            return findGitRoot(parent);
        }
    }
};

let getGitVersion = async () => {
    let root = findGitRoot();

    if (!root) {
        throw new Error("Cannot call getGitVersion from non git project.");
    }

    let rev = readFileSync(join(root, ".git/HEAD")).toString().trim();

    if (rev.indexOf(":") === -1) {
        return rev;
    } else {
        return readFileSync(join(root, ".git", rev.substring(5)))
            .toString()
            .trim();
    }
};
export default async function handler(req, res) {
    const token = await getToken({ req: req });
    if (!token) {
        // If no token or invalid token, return unauthorized status
        return res.status(401).json({ message: "Unauthorized to call this API endpoint" });
    }
    else {
        // If token is valid, log the user
        //console.log("JWT | User: " + token.email);
    }
    res.status(200).json({ v: getGitVersion() })
}