export type OnboardingMeta = {
  kind: 'onboarding';
  variant: 'initial' | 'reminder';
  part: 1 | 2;
  bundle_id: string;
  group_id?: string | null;
  task_id?: number | null;
  display_code?: number | null;
};

export type ReactionMeta = {
  kind: 'reaction';
  emoji: string;
  chatId: string;
  messageId: string;
  participant?: string;
  fromMe?: boolean;
};

export type QueueMetadata = OnboardingMeta | ReactionMeta | Record<string, any>;

export function parseQueueMetadata(raw: string | null | undefined): QueueMetadata | null {
  if (!raw) return null;
  try {
    const obj = JSON.parse(String(raw));
    if (!obj || typeof obj !== 'object') return null;
    const kind = String((obj as any).kind || '');
    if (kind === 'reaction') {
      // Validación mínima
      return {
        kind: 'reaction',
        emoji: String((obj as any).emoji || ''),
        chatId: String((obj as any).chatId || ''),
        messageId: String((obj as any).messageId || ''),
        participant: typeof (obj as any).participant === 'string' ? String((obj as any).participant) : undefined,
        fromMe: typeof (obj as any).fromMe === 'boolean' ? Boolean((obj as any).fromMe) : undefined
      } as ReactionMeta;
    }
    if (kind === 'onboarding') {
      return obj as OnboardingMeta;
    }
    return obj as Record<string, any>;
  } catch {
    return null;
  }
}

export function isReactionMeta(m: QueueMetadata | null | undefined): m is ReactionMeta {
  if (!m || typeof m !== 'object') return false;
  const any = m as any;
  return any.kind === 'reaction'
    && typeof any.chatId === 'string'
    && typeof any.messageId === 'string'
    && typeof any.emoji === 'string';
}
