import { prisma, User } from "@repo/db";
import { NextFunction } from "express";

interface AttachUserRequest extends Request {
	user?: User | null;
}

interface AttachUserMiddleware {
	(req: AttachUserRequest, res: Response, next: NextFunction): Promise<void>;
}

export const authMiddleware: AttachUserMiddleware = async (req, res, next) => {
	const authHeader = (req.headers as any).authorization;
	if (authHeader && authHeader.startsWith("User ")) {
		const userId = authHeader.split(" ")[1];
		const user = await prisma.user.findFirst({
			where: {
				id: userId,
			},
		});
		req.user = user;
	}
	next();
};
