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

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

const NEWS_PATH = path.join("content", "news");
const TERMS = ["winter", "spring", "fall"];

export interface Metadata {
  author: string;
  date: string;
}

export interface News {
  content: MDXRemoteSerializeResult;
  metadata: Metadata;
}

export async function getNewsYears(): Promise<string[]> {
  return (await fs.readdir(NEWS_PATH, { withFileTypes: true }))
    .filter((dirent) => dirent.isDirectory())
    .map((dirent) => dirent.name)
    .sort();
}

export async function getNewsTermsByYear(year: string): Promise<string[]> {
  return (
    await fs.readdir(path.join(NEWS_PATH, year), {
      withFileTypes: true,
    })
  )
    .filter((dirent) => dirent.isDirectory() && TERMS.includes(dirent.name))
    .map((dirent) => dirent.name)
    .sort((a, b) => TERMS.indexOf(a) - TERMS.indexOf(b));
}

export async function getNewsByTerm(
  year: string,
  term: string
): Promise<string[]> {
  return (
    await fs.readdir(path.join(NEWS_PATH, year, term), {
      withFileTypes: true,
    })
  )
    .filter((dirent) => dirent.isFile() && dirent.name.endsWith(".md"))
    .map((dirent) => dirent.name.slice(0, -".md".length));
}

export async function getNewsBySlug(
  year: string,
  term: string,
  slug: string
): Promise<News> {
  const raw = await fs.readFile(
    path.join(NEWS_PATH, year, term, `${slug}.md`),
    "utf-8"
  );
  const { content, data: metadata } = matter(raw);

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