import { apiHandler, db } from "@/helpers/api";

const stripe = require("stripe")(
	"sk_test_51Py980Js2Gbkz0QXEMr6KizB1SUz3LKWbCCTvEIGQruzwEzOQuT5JfBwG3ySGLyGKBKRqf6lrk4YwtLisTpqtB3a00aLYFykKT"
);

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

async function createUserCheckout(req, res) {
	const userID = req.userID;
	const formData = req.body;

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

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

		if (!userData) return res.status(404).json({ error: "Unknown!" });

		const lineItems = formData.cartProducts.map((product) => {
			const price =
				product.productPriceReduced !== undefined
					? Math.round(product.productPriceReduced * 100)
					: Math.round(product.productPrice * 100);

			return {
				price_data: {
					currency: "RON",
					product_data: {
						name: product.productName,
					},
					unit_amount: price,
				},
				quantity: product.productQuantity,
			};
		});

		const sessionParams = {
			payment_method_types: ["card"],
			line_items: lineItems,
			mode: "payment",
			success_url: `${req.headers["x-forwarded-proto"]}://${req.headers.host}/placed-order?sessionId={CHECKOUT_SESSION_ID}&userID=${userID}`,
			cancel_url: `${req.headers["x-forwarded-proto"]}://${req.headers.host}/problem-order`,
			metadata: {
				cartProducts: formData.cartProducts
					.map((product) => product.productID)
					.join(","),
				cartTotal: formData.cartTotal.toString(),
				couponCode: formData.couponCode,
			},
		};

		if (formData.couponCode.length === 10) {
			sessionParams.discounts = [
				{
					coupon: formData.couponCode,
				},
			];
		}

		const session = await stripe.checkout.sessions.create(sessionParams);

		res.json({ sessionId: session.id, url: session.url });
	} catch (error) {
		return res.status(500).json({ error: error });
	}
}
