#!/usr/bin/env bash
#
# Vérifie que le schéma WPGraphQL expose les champs attendus par le front Next.js.
# Échoue (exit 1) si un champ critique manque ("Cannot query field …") — ce qui
# arrive quand le mu-plugin déployé est plus ancien que le front (cf. l'incident
# fiche-lieu/heroImage). À lancer après tout déploiement du mu-plugin.
#
# Usage : check-graphql-schema.sh [endpoint]
#   défaut endpoint = http://127.0.0.1:8080/graphql (à lancer SUR le VPS, sans auth)
#
set -uo pipefail

EP="${1:-http://127.0.0.1:8080/graphql}"
fail=0

probe() {
  local name="$1" query="$2" resp
  resp=$(curl -s --max-time 25 "$EP" -H 'Content-Type: application/json' --data "{\"query\":\"${query}\"}" 2>/dev/null)
  if [ -z "$resp" ]; then
    echo "❌ $name : pas de réponse de $EP"; fail=1; return
  fi
  if echo "$resp" | grep -qiE 'Cannot query field|Unknown type|does not exist on type|wp_die|Internal Server Error'; then
    echo "❌ $name : schéma incomplet / erreur"
    echo "$resp" | grep -oE 'Cannot query field "[^"]+" on type "[^"]+"' | sort -u | sed 's/^/     /'
    fail=1; return
  fi
  echo "✅ $name"
}

echo "→ Vérification du schéma WPGraphQL ($EP)"

# Pages locales SEO (lieu) — l'incident : heroImage* + content.secteurs.image
probe "lieu.ficheLieu (hero + secteurs.image)" \
  '{ lieux(first:1,where:{status:PUBLISH}){ nodes { ficheLieu { heroImage { node { sourceUrl } } heroImageCredit heroImageSource content { secteurs { image { node { sourceUrl } } } } } } } }'

# i18n Polylang — language + translations (custom inc/graphql-i18n.php)
probe "produit i18n (language/translations)" \
  '{ produits(first:1,where:{status:PUBLISH}){ nodes { language { code slug } translations { language { slug } } } } }'

# Flexible content des pages
probe "page.sections (flexible content)" \
  '{ pages(first:1,where:{status:PUBLISH}){ nodes { sections { sections { __typename } } seo { titreSeo } } } }'

# Fiche produit
probe "produit.ficheProduit" \
  '{ produits(first:1,where:{status:PUBLISH}){ nodes { ficheProduit { productName sri } } } }'

# Réglages publics du widget chatbot
probe "covalbaChatbotSettings" \
  '{ covalbaChatbotSettings { enabled widgetUrl } }'

if [ "$fail" -ne 0 ]; then
  echo ""
  echo "✗ Schéma GraphQL INCOMPLET — le mu-plugin déployé est probablement obsolète."
  echo "  Re-déployer depuis main : scripts/wp/deploy-mu-plugins.sh"
  exit 1
fi
echo "✓ Schéma GraphQL OK — tous les champs attendus sont présents."
