// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
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";

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, trackingId} = req.body as {
		currencyCode: string;
		price: number;
		trackingId: string;
	};

	if (!trackingId) return res.status(401).json({ok: false, reason: "Missing tracking id!"});

	const url = `${process.env.PAYPAL_ACCESS_TOKEN_URL}/v2/checkout/orders`;
	const amount = {
		currency_code: currencyCode,
		value: price.toString(),
	};

	const data = {
		purchase_units: [
			{
				invoice_id: `INV-${v4()}`,
				amount: {
					...amount,
					breakdown: {
						item_total: amount,
					},
				},
				items: [
					{
						name: "Encoach Subscription",
						quantity: "1",
						category: "DIGITAL_GOODS",
						unit_amount: amount,
					},
				],
			},
		],
		payment_source: {
			paypal: {
				email_address: req.session.user.email || "",
				address: {
					address_line_1: "",
					address_line_2: "",
					admin_area_1: "",
					admin_area_2: "",
					// added default values as requsted by the client, using the default values recommended
					// the paypal engineer, otherwise we would have to create something that would detect the location
					// of the user and generate a valid postal code for that location...
					country_code: "US",
					postal_code: "94107",
				},
				experience_context: {
					payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED",
					locale: "en-US",
					landing_page: "LOGIN",
					shipping_preference: "NO_SHIPPING",
					user_action: "PAY_NOW",
					brand_name: "Encoach",
				},
			},
		},
		intent: "CAPTURE",
	};

	const headers = {
		headers: {
			Authorization: `Bearer ${accessToken}`,
			"PayPal-Client-Metadata-Id": trackingId,
		},
	};
	console.log(
		JSON.stringify({
			url,
			data,
			headers,
		}),
	);

	axios
		.post<OrderResponseBody>(url, data, headers)
		.then((request) => {
			res.status(request.status).json(request.data);
		})
		.catch((err) => {
			console.error(err.response.status, err.response.data);
			res.status(err.response.status).json(err.response.data);
		});
}
