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

import { DATOCMS_PREVIEW_SECRET, SITE_URL } from "@/config/constants";
import { buildPageUrl } from "@/helpers/link";

interface Item {
  id: string;
  type: string;
  attributes: {
    title: string;
    slug: string;
    seo_meta: object;
    modular_content: any[];
    structured_content: null | string;
    preview: null | string;
    updated_at: string;
    created_at: string;
  };
}

interface ItemType {
  id: string;
  type: string;
  attributes: {
    name: string;
    singleton: boolean;
    sortable: boolean;
    api_key: string;
    ordering_direction: any;
    ordering_meta: any;
    tree: boolean;
    modular_block: boolean;
    draft_mode_active: boolean;
    all_locales_required: boolean;
    collection_appeareance: string;
    collection_appearance: string;
    has_singleton_item: boolean;
    hint: any;
    inverse_relationships_enabled: boolean;
  };
}

interface DatoRecordPayload {
  item: Item;
  itemType: ItemType;
  environmentId: string;
  locale: string;
}

/**
 * Converts a DatoCMS record into a canonical URL within the website.
 * NOTE: The current implementation only supports previewing `post` records.
 */
const generatePreviewUrl = ({ item, itemType }: DatoRecordPayload) => {
  const modelApiKey = itemType.attributes.api_key;

  switch (modelApiKey) {
    case "post":
      return buildPageUrl({
        type: modelApiKey,
        slug: item?.attributes?.slug,
      });
    default:
      return null;
  }
};

const cors = Cors({
  origin: "*",
  methods: ["POST"],
  allowedHeaders: ["Content-Type", "Authorization"],
});

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(
  req: NextApiRequest,
  res: NextApiResponse,
  fn: (...args: any[]) => any,
) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result: any) => {
      if (result instanceof Error) {
        return reject(result);
      }

      return resolve(result);
    });
  });
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  // Run the middleware
  await runMiddleware(req, res, cors);

  const url = generatePreviewUrl(req.body);

  if (!url) {
    return res.status(200).json({ previewLinks: [] });
  }

  const baseUrl = SITE_URL.replace(/\/$/, "");

  const previewLinks = [
    {
      label: "Preview",
      url: `${baseUrl}/api/preview?slug=${url}&secret=${DATOCMS_PREVIEW_SECRET}`,
    },
  ];

  return res.status(200).json({ previewLinks });
}
