import { v4 } from "uuid";
import { resolve } from "path";
import { isLoggedIn } from "@server/middlewareButNotReally";
import sharp from "sharp";
import { User } from "@models/user";

export default eventHandler(async (ev) => {
	isLoggedIn(ev);
	let mpd = await readMultipartFormData(ev);
	if (!mpd) {
		throw createError({
			statusCode: 400,
		});
	}
	let si = sharp(mpd[0].data!);
	let nn = v4();
	await si
		.resize({
			height: 500,
			width: 500,
			fit: "outside",
			background: { r: 0, g: 0, b: 0, alpha: 0 },
		})
		.toFormat("png")
		.toFile(resolve(`public/avatars/${nn}.png`));
	await User.findByIdAndUpdate(ev.context.currentUser!._id, {
		$set: {
			"profile.avatar": nn,
		},
	});

	return {
		success: true,
		file: `${nn}.png`,
	};
});
