// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, collection, getDocs} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import axios from "axios";
import {v4} from "uuid";
import {OrderResponseBody} from "@paypal/paypal-js";
import {getAccessToken} from "@/utils/paypal";

const db = getFirestore(app);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method !== "POST") return res.status(404).json({ok: false, reason: "Method not supported!"});
	if (!req.session.user) return res.status(401).json({ok: false});

	const accessToken = await getAccessToken();
	if (!accessToken) return res.status(401).json({ok: false, reason: "Authorization failed!"});

	const {currencyCode, price} = req.body as {currencyCode: string; price: number};

	const request = await axios.post<OrderResponseBody>(
		`${process.env.PAYPAL_ACCESS_TOKEN_URL}/v2/checkout/orders`,
		{
			purchase_units: [
				{
					amount: {
						currency_code: currencyCode,
						value: price.toString(),
					},
					reference_id: v4(),
				},
			],
			intent: "CAPTURE",
		},
		{
			headers: {
				Authorization: `Bearer ${accessToken}`,
			},
		},
	);

	res.status(request.status).json(request.data);
}
