import type { NextApiRequest, NextApiResponse } from "next";
import moment from "moment";
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 post(req: NextApiRequest, res: NextApiResponse) {
  // verify if it's a logged user that is trying to archive
  if (req.session.user) {
    const { id } = req.query as { id: string };
    const data = await db.collection("assignments").findOne({ id: id });

    if (!data) {
      res.status(404).json({ ok: false });
      return;
    }

    if (moment().isAfter(moment(data.startDate))) {
      res
        .status(400)
        .json({ ok: false, message: "Assignment can no longer " });
      return;
    }

    await db.collection("assignments").updateOne(
      { id: id },
      { $set: { start: true } }
    );

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

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

async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "POST") return post(req, res);
  res.status(404).json({ ok: false });
}
