// 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 {Group} from "@/interfaces/user";
import {Payment} from "@/interfaces/paypal";
import {v4} from "uuid";
import ShortUniqueId from "short-unique-id";
import client from "@/lib/mongodb";

const db = client.db(process.env.MONGODB_DB);

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 payments = await db.collection("payments").find({}).toArray();

	res.status(200).json(payments);
}

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

	const shortUID = new ShortUniqueId();
	await db.collection("payments").insertOne({...body, id: shortUID.randomUUID(8)});
	res.status(200).json({ok: true});
}
