// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import client from "@/lib/mongodb";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {uuidv4} from "@firebase/util";

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

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method === "GET") return GET(req, res);
	if (req.method === "DELETE") return DELETE(req, res);

	res.status(404).json({ok: false});
}

async function GET(req: NextApiRequest, res: NextApiResponse) {
	const {id} = req.query;
	const code = await db.collection("codes").findOne({ id: id as string });

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

async function DELETE(req: NextApiRequest, res: NextApiResponse) {
	const {id} = req.query;
	const code = await db.collection("codes").findOne({ id: id as string });

	if (!code) return res.status(404).json;
	await db.collection("codes").deleteOne({ id: id as string });

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