import datasquirel from "@moduletrace/datasquirel";
import type { DATASQUIREL_LoggedInUser } from "@moduletrace/datasquirel/dist/package-shared/types";

type Param = {
    req: Request;
    debug?: boolean;
};

type Return = {
    user: DATASQUIREL_LoggedInUser | null;
};

export default async function socketInit({
    req,
    debug,
}: Param): Promise<Return> {
    const cookieString = req.headers.get("Cookie") || undefined;

    if (debug) {
        console.log("DEBUG:::socketInit:cookieString", cookieString);
    }

    if (!cookieString)
        return {
            user: null,
        };

    const user = datasquirel.user.userAuth({
        cookieString,
        database: process.env.DB_NAME || "",
    });

    if (debug) {
        console.log("DEBUG:::socketInit:user", user);
    }

    return { user: user.payload };
}
