// 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";


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") return GET(req, res);
	if (req.method === "PATCH") return PATCH(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 snapshot = await db.collection("assignments").findOne({ id: id as string });

	if (snapshot) {
		res.status(200).json({...snapshot, id: snapshot.id});
	}
}

async function DELETE(req: NextApiRequest, res: NextApiResponse) {
	const {id} = req.query;

	await db.collection("assignments").deleteOne(
		{ id: id as string }
	);

	res.status(200).json({ok: true});
}

async function PATCH(req: NextApiRequest, res: NextApiResponse) {
	const {id} = req.query;

	await db.collection("assignments").updateOne(
		{ id: id as string },
		{ $set: {assigner: req.session.user?.id, ...req.body} }
	  );

	res.status(200).json({ok: true});
}
