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

import { format } from "date-fns";

import { DATE_FORMAT } from "@/utils";

import {
  getEventsByTerm,
  getEventTermsByYear,
  getEventYears,
} from "../lib/events";
import {
  getNewsByTerm,
  getNewsTermsByYear,
  getNewsYears,
  NEWS_PATH,
} from "../lib/news";
const EVENTS_PATH = path.join("content", "events");

export async function main() {
  for (const year of await getEventYears()) {
    for (const term of await getEventTermsByYear(year)) {
      for (const slug of await getEventsByTerm(year, term)) {
        const filePath = path.join(EVENTS_PATH, year, term, `${slug}.md`);
        const file = await fs.readFile(filePath, "utf-8");

        await fs.writeFile(filePath, replaceDate(file));
      }
    }
  }

  for (const year of await getNewsYears()) {
    for (const term of await getNewsTermsByYear(year)) {
      for (const slug of await getNewsByTerm(year, term)) {
        const filePath = path.join(NEWS_PATH, year, term, `${slug}.md`);
        const file = await fs.readFile(filePath, "utf-8");

        await fs.writeFile(filePath, replaceDate(file));
      }
    }
  }
}

function replaceDate(file: string) {
  const lines = file.split("\n");
  const dateLineIdx = lines.findIndex((line) => line.startsWith("date: "));
  const dateLine = lines[dateLineIdx];
  const date = new Date(dateLine.slice("date: ".length + 1, -1));

  lines[dateLineIdx] = `date: '${format(date, DATE_FORMAT)}'`;

  return lines.join("\n");
}

void main();
