export interface Cursor {
  publishedAt: string;
  id: number;
}

export interface CursorSource {
  publishedAt: string;
  id: number;
}

export function encodeCursor(item: CursorSource | null | undefined): string | null {
  if (!item) return null;
  const payload: Cursor = { publishedAt: item.publishedAt, id: item.id };
  return Buffer.from(JSON.stringify(payload)).toString('base64url');
}

export function decodeCursor(raw: unknown): Cursor | null {
  if (!raw || typeof raw !== 'string') return null;
  try {
    const obj = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
    if (typeof obj.publishedAt !== 'string' || typeof obj.id !== 'number') return null;
    return { publishedAt: obj.publishedAt, id: obj.id };
  } catch {
    return null;
  }
}
