import fs from "fs";
import path from "path";
import matter from "gray-matter";

// 兼容 Nuxt 2（serverMiddleware）和 Nuxt 3（defineEventHandler）
const handler = (req, res) => {
  try {
    const newsDirectory = path.resolve("static/news");

    if (!fs.existsSync(newsDirectory)) {
      throw new Error("News directory does not exist");
    }

    const files = fs.readdirSync(newsDirectory);
    if (files.length === 0) {
      throw new Error("No news files found");
    }

    const newsList = files.map((file) => {
      const filePath = path.join(newsDirectory, file);
      const fileContent = fs.readFileSync(filePath, "utf-8");
      const { data } = matter(fileContent);

      return {
        title: data.title || "Untitled",
        date: data.date || "Unknown",
        slug: file.replace(".md", ""),
      };
    });

    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify(newsList));
  } catch (error) {
    console.error("API 错误:", error);
    res.statusCode = 500;
    res.end(JSON.stringify({ error: "Failed to load news", details: error.message }));
  }
};

// Nuxt 3 使用 `defineEventHandler`
export default (typeof defineEventHandler !== "undefined"
  ? defineEventHandler(() => {
      return new Promise((resolve) => {
        const fakeRes = {
          setHeader: () => {},
          end: (data) => resolve(JSON.parse(data)),
          statusCode: 200,
        };
        handler({}, fakeRes);
      });
    })
  : handler);
