import {
  BLOG_PATH,
  EVENTS_PATH,
  WORKSHOPS_PATH,
  NEWS_PATH,
  TECHNICAL_PATH,
} from "@/content.config";
import { slugifyStr } from "./slugify";

const PATHS = [
  BLOG_PATH,
  EVENTS_PATH,
  WORKSHOPS_PATH,
  NEWS_PATH,
  TECHNICAL_PATH,
];

/**
 * Get full path of a content entry
 * @param id - id of the entry (aka slug)
 * @param filePath - the entry full file location
 * @param includeBase - whether to include base path in return value
 * @returns entry path
 */
export function getPath(
  id: string,
  filePath: string | undefined,
  includeBase = true
) {
  // Determine which collection path to remove
  let basePathToRemove = BLOG_PATH;
  for (const path of PATHS) {
    if (filePath?.includes(path)) {
      basePathToRemove = path;
      break;
    }
  }

  const pathSegments = filePath
    ?.replace(basePathToRemove, "")
    .split("/")
    .filter(path => path !== "") // remove empty string in the segments ["", "other-path"] <- empty string will be removed
    .filter(path => !path.startsWith("_")) // exclude directories start with underscore "_"
    .slice(0, -1) // remove the last segment_ file name_ since it's unnecessary
    .map(segment => slugifyStr(segment)); // slugify each segment path

  // Determine base path based on collection
  let basePath = "/posts";
  if (!includeBase) {
    basePath = "";
  } else if (filePath?.includes(EVENTS_PATH)) {
    basePath = "/events";
  } else if (filePath?.includes(WORKSHOPS_PATH)) {
    basePath = "/workshops";
  } else if (filePath?.includes(NEWS_PATH)) {
    basePath = "/news";
  } else if (filePath?.includes(TECHNICAL_PATH)) {
    basePath = "/technical";
  }

  // Making sure `id` does not contain the directory
  const entryId = id.split("/");
  const slug = entryId.length > 0 ? entryId.slice(-1) : entryId;

  // If not inside the sub-dir, simply return the file path
  if (!pathSegments || pathSegments.length < 1) {
    return [basePath, slug].filter(Boolean).join("/");
  }

  return [basePath, ...pathSegments, slug].filter(Boolean).join("/");
}
