import fs from "node:fs";
import path from "node:path";
import yaml from "js-yaml";

export type DocYaml = {
  title: string;
  visible?: boolean;
  intro?: string;
  content: string; 
};

export type DocEntry = DocYaml & {
  slug: string;
  file: string;
};

const DOCS_DIR = path.join(process.cwd(), "src", "content", "document");

export function listDocuments(): DocEntry[] {
  if (!fs.existsSync(DOCS_DIR)) return [];

  const files = fs
    .readdirSync(DOCS_DIR)
    .filter((f) => /\.ya?ml$/i.test(f));

  const items: DocEntry[] = [];

  for (const file of files) {
    const full = path.join(DOCS_DIR, file);
    const raw = fs.readFileSync(full, "utf8");
    const data = (yaml.load(raw) ?? {}) as Partial<DocYaml>;

    const slug = file.replace(/\.ya?ml$/i, "");

    if (!data.title || typeof data.title !== "string") continue;
    if (!data.content || typeof data.content !== "string") continue;

    items.push({
      slug,
      file,
      title: data.title,
      visible: data.visible ?? false,
      intro: data.intro ?? "",
      content: data.content,
    });
  }

  return items;
}

export function getDocumentBySlug(slug: string): DocEntry | null {
  const candidates = [`${slug}.yaml`, `${slug}.yml`];

  for (const file of candidates) {
    const full = path.join(DOCS_DIR, file);
    if (!fs.existsSync(full)) continue;

    const raw = fs.readFileSync(full, "utf8");
    const data = (yaml.load(raw) ?? {}) as Partial<DocYaml>;

    if (!data.title || typeof data.title !== "string") return null;
    if (!data.content || typeof data.content !== "string") return null;

    return {
      slug,
      file,
      title: data.title,
      visible: data.visible ?? false,
      intro: data.intro ?? "",
      content: data.content,
    };
  }

  return null;
}
