"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = rssRoutes;
const errors_1 = require("@yinuo-ngm/errors");
const rss_parser_1 = __importDefault(require("rss-parser"));
const cache = new Map();
const parser = new rss_parser_1.default({
    timeout: 15000,
});
async function rssRoutes(app) {
    app.get("/preview", async (req) => {
        const q = req.query;
        const url = (q.url ?? "").trim();
        if (!url) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.INVALID_RSS_URL, "url required", { query: q });
        }
        const limit = Math.min(Math.max(parseInt(q.limit ?? "20", 10) || 20, 1), 100);
        const force = (q.force ?? "0") === "1";
        const cacheSec = Math.min(Math.max(parseInt(q.cacheSec ?? "2400", 10) || 2400, 30), 3600);
        const key = `${url}|${limit}`;
        const now = Date.now();
        if (!force) {
            const hit = cache.get(key);
            if (hit && hit.expireAt > now)
                return hit.payload;
        }
        try {
            const feed = await parser.parseURL(url);
            const items = (feed.items ?? []).slice(0, limit).map((it) => ({
                title: it.title ?? "",
                link: (it.link ?? it.guid ?? "").toString(),
                pubDate: it.isoDate ?? (it.pubDate ? new Date(it.pubDate).toISOString() : undefined),
                author: (it.creator ?? it.author ?? "")?.toString() || undefined,
                summary: (it.contentSnippet ?? it.content ?? "")?.toString() || undefined,
            }));
            const payload = {
                title: feed.title,
                description: feed.description,
                link: feed.link,
                items,
                fetchedAt: new Date().toISOString(),
            };
            cache.set(key, { expireAt: now + cacheSec * 1000, payload });
            return payload;
        }
        catch (e) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.RSS_FETCH_FAILED, e?.message || String(e), { url });
        }
    });
}
