import { fromNodeHeaders } from "better-auth/node";
import type { NextFunction, Request, Response } from "express";
import { auth } from "../utils/auth.utils.js";

declare global {
	namespace Express {
		interface Request {
			user?: {
				id: string;
				email?: string;
				roles?: string | null | undefined; //Record<string, string[]>;
				username?: string | null | undefined;
			};
		}
	}
}

// function toWebHeaders(nodeHeaders: Request["headers"]): Headers {
// 	const h = new Headers();
// 	for (const [key, value] of Object.entries(nodeHeaders)) {
// 		if (Array.isArray(value)) {
// 			value.forEach((v) => h.append(key, v));
// 		} else if (value !== undefined) {
// 			h.set(key, value);
// 		}
// 	}
// 	return h;
// }

export const requireAuth = async (
	req: Request,
	res: Response,
	next: NextFunction,
) => {
	try {
		const session = await auth.api.getSession({
			headers: fromNodeHeaders(req.headers),
			//query: { disableCookieCache: true },
		});

		if (!session) {
			return res.status(401).json({ error: "Unauthorized" });
		}

		//console.log(session);

		req.user = {
			id: session.user.id,
			email: session.user.email,
			roles: session.user.role,
			username: session.user.username,
		};

		next();
	} catch {
		return res.status(401).json({ error: "Unauthorized" });
	}
};
