#!/usr/bin/env bash
set -euo pipefail

###########################################
# End-to-end verification for /api/peers/*
# Requires: curl, jq, xxd, file (coreutils)
###########################################

API_KEY="${WG_API_KEY:-test-api-key}"
BASE_URL="${WG_BASE_URL:-http://127.0.0.1:8080}"

echo "[VERIF-EE] Starting end-to-end verification against ${BASE_URL}"

echo "[STEP] Seed server"
SERVER_PAYLOAD='{"name":"test-server","mode":"forward","PublicKey":"SERVER_PUBLIC_KEY_BASE64","Endpoint":"server.example:51820"}'
SERVER_ID=$(curl -s -H "wg-rplane-datadunia: ${API_KEY}" -H "Content-Type: application/json" -d "$SERVER_PAYLOAD" "$BASE_URL/api/servers" | jq -r '.id')
echo "[INFO] SERVER_ID=${SERVER_ID}"

echo "[STEP] Seed peer"
PEER_PAYLOAD='{"PublicKey":"PEER_PUBLIC_KEY_BASE64","IP":"10.0.0.2","AllowAccess":"[]","AllowInternet":false}'
PEER_ID=$(curl -s -H "wg-rplane-datadunia: ${API_KEY}" -H "Content-Type: application/json" -d "$PEER_PAYLOAD" "$BASE_URL/api/servers/${SERVER_ID}/peers" | jq -r '.id')
echo "[INFO] PEER_ID=${PEER_ID}"

echo "[STEP] Fetch config"
CONFIG_JSON=$(curl -s -w "%{http_code}" -H "wg-rplane-datadunia: ${API_KEY}" "$BASE_URL/api/peers/${PEER_ID}/config")
STATUS=$(tail -c 3 <<< "$CONFIG_JSON");
CONFIG_BODY=$(echo "$CONFIG_JSON" | sed '$d')
if [ "$STATUS" != "200" ]; then
  echo "[ERROR] Config endpoint returned status code ${STATUS}"; exit 1
fi
echo "$CONFIG_BODY" > /tmp/peer_config.conf

echo "[STEP] Validate config content"
grep -q "^\\[Interface\\]" /tmp/peer_config.conf || { echo "Config missing [Interface]"; exit 1; }
grep -q "^\\[Peer\\]" /tmp/peer_config.conf || { echo "Config missing [Peer]"; exit 1; }

echo "[STEP] Fetch QR code"
curl -s -o /tmp/peer.png -D /tmp/peer_headers.txt -H "wg-rplane-datadunia: ${API_KEY}" "$BASE_URL/api/peers/${PEER_ID}/qrcode" || { echo "Failed to fetch QR code"; exit 1; }
echo "[INFO] QR code saved to /tmp/peer.png"

echo "[STEP] Validate PNG file"
if file /tmp/peer.png | grep -qi png; then
  echo "[OK] PNG detected"
else
  echo "[ERROR] Not a PNG file"
  exit 1
fi

echo "[VERIF-EE] End-to-end verification completed successfully."
