export const encodeOffsetCursor = (offset: number): string =>
  Buffer.from(String(offset), 'utf8').toString('base64url');

export const decodeOffsetCursor = (cursor?: string): number | null => {
  if (!cursor) {
    return null;
  }

  try {
    const raw = Buffer.from(cursor, 'base64url').toString('utf8');
    const parsed = Number(raw);
    if (Number.isInteger(parsed) && parsed >= 0) {
      return parsed;
    }

    const payload = JSON.parse(raw) as { offset?: unknown };
    return Number.isInteger(payload.offset) && Number(payload.offset) >= 0
      ? Number(payload.offset)
      : null;
  } catch {
    return null;
  }
};
