import express, { Request, Response } from "express";
import fs from "fs";
import path from "path";

const router = express.Router();

const CHANGELOGS_DIR = path.resolve(__dirname, "../../changelogs");

// In-memory cache: datum → seznam změn
const cache: Record<string, string[]> = {};

function loadAllChangelogs(): Record<string, string[]> {
    let files: string[];
    try {
        files = fs.readdirSync(CHANGELOGS_DIR).filter(f => f.endsWith(".json"));
    } catch {
        return {};
    }

    for (const file of files) {
        const date = file.replace(".json", "");
        if (!cache[date]) {
            const content = fs.readFileSync(path.join(CHANGELOGS_DIR, file), "utf-8");
            cache[date] = JSON.parse(content);
        }
    }

    return cache;
}

router.get("/", (req: Request, res: Response) => {
    const all = loadAllChangelogs();
    const since = typeof req.query.since === "string" ? req.query.since : undefined;

    // Seřazení od nejnovějšího po nejstarší
    const sortedDates = Object.keys(all).sort((a, b) => b.localeCompare(a));

    const filteredDates = since
        ? sortedDates.filter(date => date > since)
        : sortedDates;

    const result: Record<string, string[]> = {};
    for (const date of filteredDates) {
        result[date] = all[date];
    }

    res.status(200).json(result);
});

export default router;
