import { isRecord } from "./rowMappers.js";
export function clampLimit(value) {
    if (!Number.isFinite(value))
        return 50;
    return Math.max(1, Math.min(200, Math.trunc(value)));
}
export function encodePermissionRequestCursor(request) {
    return Buffer.from(JSON.stringify({ createdAt: request.createdAt, id: request.id }), "utf8").toString("base64url");
}
export function encodePermissionDecisionCursor(decision) {
    return Buffer.from(JSON.stringify({ createdAt: decision.createdAt, id: decision.id }), "utf8").toString("base64url");
}
export function decodePermissionRequestCursor(cursor) {
    if (!cursor)
        return undefined;
    try {
        const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
        if (isRecord(parsed) &&
            typeof parsed.createdAt === "string" &&
            typeof parsed.id === "string") {
            return { createdAt: parsed.createdAt, id: parsed.id };
        }
    }
    catch {
        return undefined;
    }
    return undefined;
}
export function decodePermissionDecisionCursor(cursor) {
    return decodePermissionRequestCursor(cursor);
}
export function encodePermissionActivityCursor(event) {
    return Buffer.from(JSON.stringify({ at: event.at, id: event.id }), "utf8").toString("base64url");
}
export function decodePermissionActivityCursor(cursor) {
    if (!cursor)
        return undefined;
    try {
        const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
        if (isRecord(parsed) &&
            typeof parsed.at === "string" &&
            typeof parsed.id === "string") {
            return { at: parsed.at, id: parsed.id };
        }
    }
    catch {
        return undefined;
    }
    return undefined;
}
export function encodeRuntimeEventCursor(event) {
    return Buffer.from(JSON.stringify({ occurredAt: event.occurredAt, id: event.id }), "utf8").toString("base64url");
}
export function decodeRuntimeEventCursor(cursor) {
    if (!cursor)
        return undefined;
    try {
        const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
        if (isRecord(parsed) &&
            typeof parsed.occurredAt === "string" &&
            typeof parsed.id === "string") {
            return { occurredAt: parsed.occurredAt, id: parsed.id };
        }
    }
    catch {
        return undefined;
    }
    return undefined;
}
