// 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, setDoc, doc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Group} from "@/interfaces/user";
import {Payment} from "@/interfaces/paypal";
import {v4} from "uuid";
import ShortUniqueId from "short-unique-id";
import axios from "axios";
import {IntentionResult, PaymentIntention} from "@/interfaces/paymob";

const db = getFirestore(app);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user) {
		res.status(401).json({ok: false});
		return;
	}

	if (req.method === "GET") await get(req, res);
	if (req.method === "POST") await post(req, res);
}

async function get(req: NextApiRequest, res: NextApiResponse) {
	const snapshot = await getDocs(collection(db, "payments"));

	res.status(200).json(
		snapshot.docs.map((doc) => ({
			id: doc.id,
			...doc.data(),
		})),
	);
}

async function post(req: NextApiRequest, res: NextApiResponse) {
	const intention = req.body as PaymentIntention;

	const response = await axios.post<IntentionResult>(
		"https://oman.paymob.com/v1/intention/",
		{
			...intention,
			payment_methods: [parseInt(process.env.PAYMOB_INTEGRATION_ID || "0")],
			items: [],
			extras: {...intention.extras, userID: req.session.user!.id},
		} as PaymentIntention,
		{headers: {Authorization: `Token ${process.env.PAYMOB_SECRET_KEY}`}},
	);
	const intentionResult = response.data;

	res.status(200).json({
		iframeURL: `https://oman.paymob.com/unifiedcheckout/?publicKey=${process.env.PAYMOB_PUBLIC_KEY}&clientSecret=${intentionResult.client_secret}`,
	});
}
