// 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, query, where, setDoc, doc, getDoc, deleteDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";


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") 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 getDoc(doc(db, "assignments", id as string));

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

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

	await deleteDoc(doc(db, "assignments", id as string));

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

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

	await setDoc(doc(db, "assignments", id as string), {assigner: req.session.user?.id, ...req.body}, {merge: true});

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