import { apiHandler, db } from "@/helpers/api";
import formidable from "formidable";
import AWS from "aws-sdk";

export const config = {
	api: {
		bodyParser: false, 
	},
};

export default apiHandler({
	post: updateMarketplaceAvatar,
});

async function parseForm(req) {
	return new Promise((resolve, reject) => {
		const form = formidable({
			maxFileSize: 5 * 1024 * 1024, 
			allowEmptyFiles: false,
			multiples: false,
		});

		form.parse(req, (err, fields, files) => {
			if (err) reject(err);
			resolve({ fields, files });
		});
	});
}

async function updateMarketplaceAvatar(req, res) {
	const userID = req.userID;

	if (!db.initialized) await db.initialize();

	try {
		const userData = await db.User.findByPk(userID);

		if (!userData) return res.status(404).json({ error: "Unknown!" });
		if (userData.id !== userID) return res.status(401).json({ error: "Unauthorized!" });
		if (userData.marketplace === 0) return res.status(401).json({ error: "Unauthorized!" });

		const { files } = await parseForm(req);

		if (!files.avatar) return res.status(400).json({ error: "Imaginea nu a fost trimisă." });

		const file = Array.isArray(files.avatar) ? files.avatar[0] : files.avatar;

		const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/jpg"];
		if (!allowedTypes.includes(file.mimetype)) {
			return res.status(400).json({ error: "Format invalid. Doar JPG/PNG/WEBP." });
		}

		const s3 = new AWS.S3({
			accessKeyId: 'AKIA2AFW3Y3G5AFYQX6F',
			secretAccessKey: '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',
			region: 'eu-north-1',
		});

		const fileName = `avatar/${userID}_${Date.now()}`;

		const fs = require("fs");
		const fileBuffer = fs.readFileSync(file.filepath);

		const uploadResult = await s3
			.upload({
				Bucket: 'emagyl',
				Key: fileName,
				Body: fileBuffer,
				ContentType: file.mimetype,
				ACL: "public-read",
			})
			.promise();

		const imageUrl = uploadResult.Location;

		await db.User.update({ marketplace_avatar: imageUrl }, { where: { id: userID } });

		return res.status(200).json({ url: imageUrl });
	} catch (error) {
		console.error(error);
		return res.status(500).json({ error: "Eroare la actualizarea avatarului." });
	}
}
