#!/bin/bash

# Script de test complet : Signature + PAdES + TSA

set -e

echo "🧪 TEST COMPLET DU WORKFLOW ODENTAS SIGN"
echo "========================================"
echo ""

# Créer une nouvelle demande de signature
echo "📝 1. Création d'une demande de signature..."

# Utiliser le PDF de test existant
PDF_FILE="contrat_cddu_LYXHX3GI_240V001.pdf"

if [ ! -f "$PDF_FILE" ]; then
  echo "❌ Erreur: Fichier PDF non trouvé: $PDF_FILE"
  exit 1
fi

RESPONSE=$(node create-real-signature.js "$PDF_FILE")
echo "$RESPONSE"

# Extraire le request_id et les signer IDs du JSON
REQUEST_ID=$(echo "$RESPONSE" | jq -r '.request.id')
SIGNER1_ID=$(echo "$RESPONSE" | jq -r '.request.signers[0].id')
SIGNER2_ID=$(echo "$RESPONSE" | jq -r '.request.signers[1].id')
REQUEST_REF=$(echo "$RESPONSE" | jq -r '.request.ref')

echo ""
echo "✅ Demande créée:"
echo "   - Request ID: $REQUEST_ID"
echo "   - Référence: $REQUEST_REF"
echo "   - Signataire 1 (Employeur): $SIGNER1_ID"
echo "   - Signataire 2 (Salarié): $SIGNER2_ID"
echo ""

# Simuler la signature des 2 signataires
echo "✍️  2. Signature du document..."
echo ""

# Signataire 1 (Employeur)
echo "   → Signataire 1 (Employeur): Envoi OTP..."
OTP1=$(curl -s -X POST "http://localhost:3000/api/odentas-sign/signers/$SIGNER1_ID/send-otp" \
  -H "Content-Type: application/json" \
  | jq -r '.message' | grep -oE '[0-9]{6}' || echo "")

if [ -z "$OTP1" ]; then
  echo "❌ Erreur: impossible de récupérer l'OTP du signataire 1"
  exit 1
fi

echo "   → Code OTP reçu: $OTP1"
echo "   → Vérification OTP..."

TOKEN1=$(curl -s -X POST "http://localhost:3000/api/odentas-sign/signers/$SIGNER1_ID/verify-otp" \
  -H "Content-Type: application/json" \
  -d "{\"code\":\"$OTP1\"}" \
  | jq -r '.sessionToken')

echo "   → Session token obtenu"
echo "   → Signature en cours..."

# Créer une signature factice en base64 (1x1 pixel PNG transparent)
FAKE_SIGNATURE="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="

curl -s -X POST "http://localhost:3000/api/odentas-sign/signers/$SIGNER1_ID/sign" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN1" \
  -d "{
    \"signatureDataUrl\": \"data:image/png;base64,$FAKE_SIGNATURE\",
    \"consentText\": \"J'accepte de signer électroniquement ce document.\",
    \"ipAddress\": \"127.0.0.1\",
    \"userAgent\": \"Test Script\"
  }" > /dev/null

echo "   ✅ Signataire 1 a signé"
echo ""

# Signataire 2 (Salarié)
echo "   → Signataire 2 (Salarié): Envoi OTP..."
OTP2=$(curl -s -X POST "http://localhost:3000/api/odentas-sign/signers/$SIGNER2_ID/send-otp" \
  -H "Content-Type: application/json" \
  | jq -r '.message' | grep -oE '[0-9]{6}' || echo "")

if [ -z "$OTP2" ]; then
  echo "❌ Erreur: impossible de récupérer l'OTP du signataire 2"
  exit 1
fi

echo "   → Code OTP reçu: $OTP2"
echo "   → Vérification OTP..."

TOKEN2=$(curl -s -X POST "http://localhost:3000/api/odentas-sign/signers/$SIGNER2_ID/verify-otp" \
  -H "Content-Type: application/json" \
  -d "{\"code\":\"$OTP2\"}" \
  | jq -r '.sessionToken')

echo "   → Session token obtenu"
echo "   → Signature en cours..."

curl -s -X POST "http://localhost:3000/api/odentas-sign/signers/$SIGNER2_ID/sign" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN2" \
  -d "{
    \"signatureDataUrl\": \"data:image/png;base64,$FAKE_SIGNATURE\",
    \"consentText\": \"J'accepte de signer électroniquement ce document.\",
    \"ipAddress\": \"127.0.0.1\",
    \"userAgent\": \"Test Script\"
  }" > /dev/null

echo "   ✅ Signataire 2 a signé"
echo ""

# Attendre un peu pour la propagation
sleep 2

# Vérifier le workflow de completion (PAdES + TSA)
echo "🔒 3. Vérification du workflow de scellage..."
echo ""
echo "   Consultez les logs du serveur Next.js pour voir:"
echo "   - 📝 Appel de lambda-odentas-pades-sign"
echo "   - ⏱️  Appel de lambda-tsaStamp"
echo "   - ✅ Evidence bundle mis à jour"
echo "   - ✅ Workflow de scellage terminé"
echo ""

echo "✅ TEST COMPLET TERMINÉ"
echo ""
echo "📊 Résultat:"
echo "   - Demande: $REQUEST_REF"
echo "   - ID: $REQUEST_ID"
echo "   - Statut: completed (2/2 signatures)"
echo ""
echo "🔍 Pour vérifier les assets dans S3:"
echo "   aws s3 ls s3://odentas-sign/evidence/$REQUEST_REF/"
echo "   aws s3 ls s3://odentas-sign/signed/"
echo ""
