import jwt from "jsonwebtoken";
import { IUser, User } from "@models/user";

export default defineEventHandler(async (event) => {
	let ahead = (getHeaders(event).authorization || getHeaders(event).Authorization || getCookie(event, "rockfic_cookie"))?.replace("Bearer ", "");
	if (ahead) {
		let toktok: any;
		let user: IUser | null = null;
		try {
			toktok = jwt.verify(ahead, useRuntimeConfig().jwt);
			console.log(toktok);
			if (toktok?.sub) {
				user = await User.findById(toktok.sub as number)
					.select("-password -auth -ipLog")
					.exec();
			} else if (toktok.id) {
				user = await User.findById(toktok.id as number)
					.select("-password -auth -ipLog")
					.exec();
			}
		} catch (E) {
			console.error(E);
		} finally {
			if (user) event.context.currentUser = user;
		}
	}
});
