import fs from "fs/promises";
import path from "path";

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

export interface Metadata {
  slug: string;
  index: number;
  title: string;
  presentors: string[];
  thumbnails: { small: string; large?: string };
  links: { file: string; type: string; size?: string }[];
}

const TALKS_PATH = path.join("content", "resources", "tech-talks");

export async function getTechTalk(slug: string) {
  const raw = await fs.readFile(path.join(TALKS_PATH, `${slug}.md`));
  const { content, data: metadata } = matter(raw);

  return {
    content: await serialize(content),
    metadata: { ...metadata, slug } as Metadata,
  };
}

export async function getTechTalkNames() {
  return (await fs.readdir(TALKS_PATH))
    .filter((name) => name.endsWith(".md"))
    .map((name) => name.slice(0, -1 * ".md".length));
}

export async function getTechTalks() {
  const names = await getTechTalkNames();
  const talks = await Promise.all(names.map(getTechTalk));

  return talks.sort((a, b) => a.metadata.index - b.metadata.index);
}
