#!/bin/bash
set -e

# Script de test complet du workflow Odentas Sign
# 1. Upload PDF test dans S3 (déclenche Lambda conversion)
# 2. Création signature request via API
# 3. Envoi OTP et signature électronique
# 4. Application PAdES (signature PDF)
# 5. Horodatage TSA
# 6. Compliance lock dans bucket odentas-sign

echo "========================================="
echo "🧪 Test complet Odentas Sign Workflow"
echo "========================================="
echo ""

# Variables
REQUEST_ID="TEST-$(date +%s)"
PDF_FILE="test-contrat.pdf"
SOURCE_BUCKET="odentas-sign"
DEST_BUCKET="odentas-docs"
API_BASE="http://localhost:3000"

echo "📋 Configuration:"
echo "  - Request ID: $REQUEST_ID"
echo "  - PDF: $PDF_FILE"
echo "  - API: $API_BASE"
echo ""

# Étape 1: Upload PDF dans S3 (déclenche conversion automatique)
echo "📤 Étape 1: Upload PDF dans S3..."
aws s3 cp "$PDF_FILE" "s3://$SOURCE_BUCKET/source/test/$REQUEST_ID.pdf"
echo "✅ PDF uploadé: s3://$SOURCE_BUCKET/source/test/$REQUEST_ID.pdf"
echo ""

# Attendre la conversion Lambda
echo "⏳ Attente conversion Lambda (15s)..."
sleep 15
echo ""

# Vérifier que les images sont générées
echo "🔍 Vérification images converties..."
IMAGE_COUNT=$(aws s3 ls "s3://$DEST_BUCKET/odentas-sign-images/$REQUEST_ID/" | wc -l)
echo "✅ $IMAGE_COUNT image(s) générée(s)"
echo ""

# Afficher les logs Lambda
echo "📋 Logs Lambda (dernière exécution):"
aws logs tail /aws/lambda/odentas-sign-pdf-converter --since 2m --region eu-west-3 --format short | grep -E "($REQUEST_ID|page|✅)" || echo "Pas de logs pour $REQUEST_ID"
echo ""

# Étape 2: Créer une signature request via API
echo "📝 Étape 2: Création signature request..."
SIGNER_EMAIL="test-$(date +%s)@example.com"
SIGNER_NAME="Test Signer"

CREATE_RESPONSE=$(curl -s -X POST "$API_BASE/api/odentas-sign/requests" \
  -H "Content-Type: application/json" \
  -d "{
    \"documentKey\": \"source/test/$REQUEST_ID.pdf\",
    \"signers\": [
      {
        \"email\": \"$SIGNER_EMAIL\",
        \"name\": \"$SIGNER_NAME\",
        \"signatureFields\": [
          {
            \"page\": 1,
            \"x\": 100,
            \"y\": 100,
            \"width\": 200,
            \"height\": 50
          }
        ]
      }
    ]
  }")

echo "$CREATE_RESPONSE" | jq '.'
SIGNATURE_REQUEST_ID=$(echo "$CREATE_RESPONSE" | jq -r '.id')
SIGNER_ID=$(echo "$CREATE_RESPONSE" | jq -r '.signers[0].id')

echo "✅ Request créée: $SIGNATURE_REQUEST_ID"
echo "✅ Signer ID: $SIGNER_ID"
echo ""

# Étape 3: Récupérer l'OTP depuis les logs
echo "🔐 Étape 3: Envoi OTP..."
sleep 2

# Simuler l'envoi d'OTP (normalement par email)
OTP_RESPONSE=$(curl -s -X POST "$API_BASE/api/odentas-sign/requests/$SIGNATURE_REQUEST_ID/signers/$SIGNER_ID/otp")
echo "$OTP_RESPONSE" | jq '.'

# Récupérer l'OTP depuis les logs API (mode dev)
echo "📋 Recherche OTP dans les logs..."
OTP_CODE=$(grep -A 5 "OTP généré" .next/server.log 2>/dev/null | grep -oE '[0-9]{6}' | tail -1 || echo "")

if [ -z "$OTP_CODE" ]; then
  echo "⚠️  OTP non trouvé dans les logs, utilisez '123456' par défaut"
  OTP_CODE="123456"
fi

echo "🔑 OTP: $OTP_CODE"
echo ""

# Étape 4: Vérifier l'OTP
echo "✅ Étape 4: Vérification OTP..."
VERIFY_RESPONSE=$(curl -s -X POST "$API_BASE/api/odentas-sign/requests/$SIGNATURE_REQUEST_ID/signers/$SIGNER_ID/verify-otp" \
  -H "Content-Type: application/json" \
  -d "{\"otp\": \"$OTP_CODE\"}")

echo "$VERIFY_RESPONSE" | jq '.'
SESSION_TOKEN=$(echo "$VERIFY_RESPONSE" | jq -r '.sessionToken')
echo "✅ Session token obtenu"
echo ""

# Étape 5: Signer le document
echo "✍️  Étape 5: Signature électronique..."
SIGN_RESPONSE=$(curl -s -X POST "$API_BASE/api/odentas-sign/requests/$SIGNATURE_REQUEST_ID/signers/$SIGNER_ID/sign" \
  -H "Content-Type: application/json" \
  -H "X-Session-Token: $SESSION_TOKEN" \
  -d "{
    \"signatureImage\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"
  }")

echo "$SIGN_RESPONSE" | jq '.'
echo "✅ Signature appliquée"
echo ""

# Étape 6: Vérifier le statut PAdES
echo "📄 Étape 6: Vérification signature PAdES..."
sleep 3

STATUS_RESPONSE=$(curl -s "$API_BASE/api/odentas-sign/requests/$SIGNATURE_REQUEST_ID")
echo "$STATUS_RESPONSE" | jq '.status, .signers[0].status, .pades_applied, .tsa_applied'
echo ""

# Étape 7: Vérifier TSA
echo "🕐 Étape 7: Vérification horodatage TSA..."
TSA_STATUS=$(echo "$STATUS_RESPONSE" | jq -r '.tsa_applied')
if [ "$TSA_STATUS" = "true" ]; then
  echo "✅ Horodatage TSA appliqué"
else
  echo "⏳ Horodatage TSA en cours..."
fi
echo ""

# Étape 8: Vérifier compliance lock dans S3
echo "🔒 Étape 8: Vérification compliance lock..."
SIGNED_KEY="signed/$REQUEST_ID-signed.pdf"

# Attendre que le PDF signé soit disponible
sleep 5

LOCK_STATUS=$(aws s3api head-object \
  --bucket "$SOURCE_BUCKET" \
  --key "$SIGNED_KEY" \
  --query 'ObjectLockMode' \
  --output text 2>/dev/null || echo "NOT_FOUND")

if [ "$LOCK_STATUS" = "COMPLIANCE" ]; then
  echo "✅ Compliance lock activé sur le PDF signé"
  
  # Afficher la date d'expiration du lock
  RETAIN_UNTIL=$(aws s3api head-object \
    --bucket "$SOURCE_BUCKET" \
    --key "$SIGNED_KEY" \
    --query 'ObjectLockRetainUntilDate' \
    --output text)
  echo "📅 Verrouillé jusqu'au: $RETAIN_UNTIL"
else
  echo "⚠️  Compliance lock non trouvé (status: $LOCK_STATUS)"
fi
echo ""

# Résumé final
echo "========================================="
echo "✅ Test complet terminé!"
echo "========================================="
echo ""
echo "📊 Résumé:"
echo "  - Request ID: $SIGNATURE_REQUEST_ID"
echo "  - Signer: $SIGNER_NAME ($SIGNER_EMAIL)"
echo "  - Images converties: $IMAGE_COUNT"
echo "  - PAdES: $(echo "$STATUS_RESPONSE" | jq -r '.pades_applied')"
echo "  - TSA: $(echo "$STATUS_RESPONSE" | jq -r '.tsa_applied')"
echo "  - Compliance lock: $LOCK_STATUS"
echo ""
echo "🔗 Liens utiles:"
echo "  - PDF source: https://s3.console.aws.amazon.com/s3/object/$SOURCE_BUCKET?prefix=source/test/$REQUEST_ID.pdf"
echo "  - Images: https://s3.console.aws.amazon.com/s3/buckets/$DEST_BUCKET?prefix=odentas-sign-images/$REQUEST_ID/"
echo "  - PDF signé: https://s3.console.aws.amazon.com/s3/object/$SOURCE_BUCKET?prefix=$SIGNED_KEY"
echo ""
