"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetadataCache = void 0;
const tslib_1 = require("tslib");
const hasha_1 = tslib_1.__importDefault(require("hasha"));
const packageCache = tslib_1.__importStar(require("../../../util/cache/package"));
const http_1 = require("../../../util/http");
const url_1 = require("../../../util/url");
const schema_1 = require("./schema");
class MetadataCache {
    http;
    constructor(http) {
        this.http = http;
    }
    async getRelease(registryUrl, packageName, versions) {
        const hash = (0, hasha_1.default)(versions, { algorithm: 'sha256' });
        const cacheNs = `datasource-rubygems`;
        const cacheKey = `metadata-cache:${registryUrl}:${packageName}`;
        const oldCache = await packageCache.get(cacheNs, cacheKey);
        if (oldCache?.hash === hash) {
            return oldCache.data;
        }
        try {
            const { body: releases } = await this.http.getJson((0, url_1.joinUrlParts)(registryUrl, '/api/v1/versions', `${packageName}.json`), schema_1.GemVersions);
            const { body: metadata } = await this.http.getJson((0, url_1.joinUrlParts)(registryUrl, '/api/v1/gems', `${packageName}.json`), schema_1.GemMetadata);
            const data = { releases };
            if (metadata.changelogUrl) {
                data.changelogUrl = metadata.changelogUrl;
            }
            if (metadata.sourceUrl) {
                data.sourceUrl = metadata.sourceUrl;
            }
            if (metadata.homepage) {
                data.homepage = metadata.homepage;
            }
            const newCache = { hash, data };
            const ttlMinutes = 100 * 24 * 60;
            const ttlRandomDelta = Math.floor(Math.random() * 10 * 24 * 60);
            await packageCache.set(cacheNs, cacheKey, newCache, ttlMinutes + ttlRandomDelta);
            return data;
        }
        catch (err) {
            if (err instanceof http_1.HttpError && err.response?.statusCode === 404) {
                const releases = versions.map((version) => ({ version }));
                return { releases };
            }
            throw err;
        }
    }
}
exports.MetadataCache = MetadataCache;
//# sourceMappingURL=metadata-cache.js.map