import { readFile, readdir, access } from "fs/promises";
import path from "path";

import matter from "gray-matter";
import { serialize } from "next-mdx-remote/serialize";

const EXECS_PATH = path.join("content", "team", "execs");
const fileType = ".md";

export interface Metadata {
  name: string;
  role: string;
  image: string;
}

export async function getExecNames() {
  return (await readdir(EXECS_PATH))
    .filter((name) => name.endsWith(fileType))
    .map((name) => name.slice(0, -1 * fileType.length));
}

export async function getExec(fileName: string, convert = true) {
  const raw = await readFile(path.join(EXECS_PATH, `${fileName}${fileType}`));
  const { content, data: metadata } = matter(raw);
  const image =
    (metadata.image as string | undefined) ??
    (await getMemberImagePath(metadata.name));

  return {
    content: convert ? await serialize(content) : content,
    metadata: { ...metadata, image } as Metadata,
  };
}

async function getImage(imgPath: string) {
  try {
    await access(path.join("public", imgPath));
    return imgPath;
  } catch {
    return undefined;
  }
}

export async function getMemberImagePath(name: string) {
  const imgPath = path.join("images", "team", name.replace(" ", ""));
  const placeholder = path.join(
    "images",
    "team",
    "team-member-placeholder.svg"
  );
  const img =
    (await getImage(imgPath + ".jpg")) ??
    (await getImage(imgPath + ".png")) ??
    (await getImage(imgPath + ".gif")) ??
    (await getImage(imgPath + ".jpeg")) ??
    placeholder;
  return img;
}
