#!/bin/bash
# Evolution API v2.4.0 — Connect instance via QR code or pairing code
API_URL="http://177.153.38.26:8080"
API_KEY="429683C4C977415CAAFCCE10F7D57E11"
INSTANCE="${1:-eu-testeeeeee}"
NUMBER=""

# Parse --pairing / -p flag
if [ "$2" = "--pairing" ] || [ "$2" = "-p" ]; then
  NUMBER="${3:-555199309404}"
fi

if [ -n "$NUMBER" ]; then
  echo "📲 Conectando $INSTANCE via pairing code ($NUMBER) ..."
  resp=$(curl -sf -X GET "$API_URL/instance/connect/$INSTANCE?number=$NUMBER" -H "apikey: $API_KEY") || {
    echo "❌ Erro ao conectar" >&2; exit 1
  }
else
  echo "📲 Conectando $INSTANCE via QR code ..."
  resp=$(curl -sf -X GET "$API_URL/instance/connect/$INSTANCE" -H "apikey: $API_KEY") || {
    echo "❌ Erro ao conectar" >&2; exit 1
  }
fi

pair=$(echo "$resp" | jq -r '.pairingCode // empty')
b64=$(echo "$resp" | jq -r '.base64 // empty')

if [ -n "$pair" ]; then
  echo "✅ Pairing code: $pair"
fi

if [ -n "$b64" ]; then
  file="qr-$INSTANCE.png"
  echo "$b64" | sed 's/^data:image\/png;base64,//' | base64 -d > "$file" 2>/dev/null
  echo "✅ QR code salvo em: $file ($(wc -c < "$file") bytes)"
fi
