"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toCloudSafeId = toCloudSafeId;
const legacyUuidPattern = /^[a-fA-F0-9-]{36}$/;
const untypedUidPattern = /^[a-zA-Z0-9_-]+$/;
const typedUidPattern = /^(?<id>[a-zA-Z0-9_-]{22})-(?<type>[a-z]+)$/;
const idTypes = {
    uuid: 1,
    untypedUid: 2,
    typedUid: 3,
};
function isLegacyUuid(id) {
    return !!id.match(legacyUuidPattern);
}
function isUntypedUid(id) {
    return !!id.match(untypedUidPattern);
}
function isTypedUid(id) {
    return !!id.match(typedUidPattern);
}
function legacyUuidToHex(id) {
    const idTypeBuffer = Buffer.alloc(1, idTypes.uuid);
    const idBuffer = Buffer.from(id.toLowerCase().replace(/-/g, ''), 'hex');
    return Buffer.concat([idTypeBuffer, idBuffer]).toString('hex');
}
function untypedUidToHex(id) {
    const idTypeBuffer = Buffer.alloc(1, idTypes.untypedUid);
    const idBuffer = Buffer.from(id.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
    return Buffer.concat([idTypeBuffer, idBuffer]).toString('hex');
}
function typedUidToHex(typedUid) {
    const { id, type } = typedUid.match(typedUidPattern)
        .groups;
    const idTypeBuffer = Buffer.alloc(1, idTypes.typedUid);
    const idBuffer = Buffer.from(id.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
    const typeBuffer = Buffer.from(type, 'utf8');
    return Buffer.concat([idTypeBuffer, idBuffer, typeBuffer]).toString('hex');
}
function hexToBase36(hex) {
    return BigInt(`0x${hex}`).toString(36);
}
function toCloudSafeId(id) {
    if (!id) {
        throw new Error('id is required');
    }
    if (isLegacyUuid(id)) {
        return hexToBase36(legacyUuidToHex(id));
    }
    if (isTypedUid(id)) {
        return hexToBase36(typedUidToHex(id));
    }
    if (isUntypedUid(id)) {
        return hexToBase36(untypedUidToHex(id));
    }
    throw new Error(`Not a valid ID: [${id}]`);
}
