import mongoose from "mongoose";
import jwt from "jsonwebtoken";
import { IUser, User } from "~/models/user";
import { log } from "~/lib/server/logger";

export default eventHandler(async (event) => {
	const wrongMsg = "wrong credentials";
	let reqbody = await readBody(event);
	let user = await User.findOne({ username: reqbody.username }).exec();
	log.debug(reqbody, { label: "login/body" });
	log.debug("USER -> " + user, { label: "login" });
	log.debug("conn ->" + mongoose.connection, { label: "login" });
	let cok = getHeader(event, "Authorization")?.replace("Bearer ", "");
	if (!cok) {
		if (!user) {
			throw createError({ statusCode: 401, message: wrongMsg });
		}
		if (user.banned) {
			throw createError({
				statusCode: 401,
				message: "This account has been banned.",
			});
		}
		if (user.validPassword(reqbody.password)) {
			if (!user.auth.emailVerified) {
				throw createError({
					statusCode: 401,
					message:
						'Account inactive!<br><a href="/activate/resend">Resend verification</a>?',
				});
			}
			let tok = user.generateToken(useRuntimeConfig().jwt);
			// setCookie(event, "rockfic_cookie", tok);
			return {
				user,
				token: tok,
			};
		} else {
			throw createError({ statusCode: 401, message: wrongMsg });
		}
	} else {
		if (jwt.verify(cok, useRuntimeConfig().jwt)) {
			throw createError({
				statusCode: 405,
				message: "Already logged in.",
			});
		} else {
			throw createError({ statusCode: 401, message: wrongMsg });
		}
	}
});
