import { unwrapArray } from "@/helpers/array";
import { type BasePage, type LinkRecord } from "@/types";

export const isExternalUrl = (url: string) => /^https?:\/\//.test(url);

export const getLinkRecord = (link: LinkRecord | LinkRecord[]) => {
  const linkRecord = unwrapArray(link);

  if (
    !linkRecord ||
    (!linkRecord.destinationUrl && !linkRecord.destinationPage)
  )
    return null;

  return linkRecord;
};

export const getLink = (link: LinkRecord | LinkRecord[]) => {
  const linkRecord = getLinkRecord(link);
  // If link destination is a URL
  if (linkRecord && linkRecord.destinationUrl) {
    return linkRecord.destinationUrl;
  }

  // If link destination is a page
  if (linkRecord && linkRecord.destinationPage) {
    const page = linkRecord.destinationPage;
    return buildPageUrl(page);
  }

  return null;
};

export const buildPageUrl = ({
  type,
  slug,
}: Pick<BasePage, "type" | "slug">) => {
  return type === "post" ? `/blog/${slug}` : `/${slug === "home" ? "" : slug}`;
};

export function parsePageUrl(path?: string | null): {
  root: string | null;
  slug: string;
} | null {
  if (!path) return null;

  if (path === "/") {
    return {
      root: null,
      slug: "home",
    };
  }

  const parts = path.split("/").filter(Boolean);

  if (parts.length === 1) {
    return {
      root: null,
      slug: parts[0],
    };
  } else if (parts.length === 2) {
    return {
      root: parts[0],
      slug: parts[1],
    };
  }

  return null;
}
