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

import { DATOCMS_PREVIEW_SECRET } from "@/config/constants";
import { unwrapArray } from "@/helpers/array";
import { buildPageUrl, parsePageUrl } from "@/helpers/link";
import { getPostBySlug } from "@/lib/api";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<any>,
) {
  // This secret should only be known to this API route and the CMS
  if (req.query.secret !== DATOCMS_PREVIEW_SECRET) {
    return res.status(401).json({ message: "Invalid token" });
  }

  // Check the `slug` parameter
  if (!req.query.slug) {
    return res
      .status(404)
      .json({ message: "The `slug` parameter is required" });
  }

  const slug = unwrapArray(req.query.slug);
  const path = parsePageUrl(slug);

  if (!path) {
    return res.status(401).json({ message: "Invalid slug" });
  }

  const record = await getPostBySlug(path.slug, true);

  // If the slug doesn't return a valid record, prevent preview mode from being enabled
  if (!record) {
    return res.status(401).json({ message: "Invalid record" });
  }

  // Enable draft mode by setting the cookie
  res.setDraftMode({ enable: true });

  // Redirect to the path from the fetched page.
  // We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities.
  const location = buildPageUrl(record);
  res.redirect(location);
}
