import * as remeda from "remeda";
import { timestamp } from "../util.js";
// Selects the most recent community record across the gateway responses, returning the winner
// together with ITS OWN resolved ipnsHops. Pure (no `this`) so the winner/hops binding can be
// unit-tested directly — gateways race and can resolve different chains, so the hops must come
// from the gateway whose record we actually keep, not whichever callback wrote last.
export function selectWinningGatewayCommunity(opts) {
    const { gatewayFetches, currentUpdatedAt, totalGateways, fallbackIpnsName } = opts;
    const gatewaysWithCommunity = remeda.keys.strict(gatewayFetches).filter((gatewayUrl) => gatewayFetches[gatewayUrl].communityRecord);
    if (gatewaysWithCommunity.length === 0)
        return undefined;
    const gatewaysWithError = remeda.keys.strict(gatewayFetches).filter((gatewayUrl) => gatewayFetches[gatewayUrl].error);
    const bestGatewayUrl = (remeda.maxBy(gatewaysWithCommunity, (gatewayUrl) => gatewayFetches[gatewayUrl].communityRecord.updatedAt));
    const best = gatewayFetches[bestGatewayUrl];
    if (best.communityRecord.updatedAt > currentUpdatedAt)
        return {
            community: best.communityRecord,
            cid: best.cid,
            ipnsHops: best.ipnsHops ?? [fallbackIpnsName],
            bestGatewayUrl,
            recordAgeSeconds: timestamp() - best.communityRecord.updatedAt
        };
    // We weren't able to find any new community records
    if (gatewaysWithError.length + gatewaysWithCommunity.length === totalGateways)
        return undefined;
    return undefined;
}
//# sourceMappingURL=community-gateway-selection.js.map