// import { MUser } from "@/model/sequelize/User";
// import { MAuth } from "@/model/sequelize/Auth";

import { validatepassword } from "@/util/auth";
import { APIError } from "@/util/api/error";
import { User } from "@/models";

export function parseBasicAuth(authb64: string): UserAuth {
	const authString: string = Buffer.from(
		authb64.split(" ")[1] as any,
		"base64"
	).toString("utf8");
	var userAuth: UserAuth = {
		username: authString.split(":")[0] as any,
		password: authString.split(":")[1] as any,
	};
	return userAuth;
}

export type UserAuth = {
	username: string;
	password: string;
};

export async function getAssociatedUser(auth: UserAuth) {
	let foundUser = await User.findOne({
		attributes: { include: ["password"] },
		where: { username: auth.username },
	});

	if (!foundUser)
		throw new APIError({
			status: 401,
			responseText: "Unauthorized: Invalid Username",
		});

	if (!(await validatepassword(auth.password, foundUser.password)))
		throw new APIError({
			status: 401,
			responseText: "Unauthorized: Invalid Password",
		});

	return foundUser;
}
