import type { NextApiRequest, NextApiResponse } from "next";

import { unwrapArray } from "@/helpers/array";

/**
 * Uses the query parameters of the given request object to return a redirect URL.
 */
const getRedirectUrl = (req: NextApiRequest) => {
  let redirectUrl = "/";

  if (req.query?.redirect_url) {
    redirectUrl = unwrapArray(req.query?.redirect_url);
  } else if (req.query?.slug) {
    redirectUrl = unwrapArray(req.query.slug);

    if (redirectUrl == "/home") {
      redirectUrl = "/";
    }
  }

  return redirectUrl;
};

/**
 * Cancels preview by clearing Next preview mode cookies.
 */
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<any>,
) {
  // Clear the draft mode cookie
  res.setDraftMode({ enable: false });

  const redirectUrl = getRedirectUrl(req);

  // Redirect to page
  res.redirect(redirectUrl);
  res.end();
}
