/**
 * Test complet: Signature + Création de la preuve + Génération du PDF de preuve
 * 
 * Prérequis:
 * 1. Migration Supabase appliquée
 * 2. Serveur dev lancé (npm run dev)
 * 3. Authentification Supabase valide
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const OUTPUT_DIR = path.join(__dirname, 'test-signature-output');
const VERIFICATION_DATA_PATH = path.join(OUTPUT_DIR, 'verification-data.json');
const API_URL = 'http://localhost:3000';

async function main() {
  console.log('🧪 Test complet: Création de preuve de signature\n');

  // Vérifier que les données de signature existent
  if (!fs.existsSync(VERIFICATION_DATA_PATH)) {
    console.error('❌ Fichier verification-data.json non trouvé!');
    console.error('   Exécutez d\'abord: node test-signature-complete.mjs\n');
    process.exit(1);
  }

  // Charger les données de vérification
  const verificationData = JSON.parse(fs.readFileSync(VERIFICATION_DATA_PATH, 'utf-8'));
  console.log('✅ Données de vérification chargées\n');

  // Note: Pour appeler l'API, il faut être authentifié
  // En production, l'API serait appelée depuis le frontend avec une session valide
  console.log('📝 Données à envoyer à l\'API:');
  console.log(JSON.stringify(verificationData, null, 2));
  console.log('\n');

  console.log('🔧 Pour tester manuellement:\n');
  console.log('1. Appliquez la migration Supabase:');
  console.log('   supabase db push');
  console.log('   OU');
  console.log('   Copiez le contenu de supabase/migrations/20251028_signature_verifications.sql');
  console.log('   dans le SQL Editor de Supabase Dashboard\n');
  
  console.log('2. Lancez le serveur dev:');
  console.log('   npm run dev\n');
  
  console.log('3. Visitez:');
  console.log(`   ${API_URL}/test-signature-verification\n`);
  
  console.log('4. Le système va automatiquement:');
  console.log('   ✅ Créer une entrée dans signature_verifications');
  console.log('   ✅ Générer un QR code');
  console.log('   ✅ Créer un PDF de preuve');
  console.log('   ✅ Afficher l\'URL de vérification publique\n');

  console.log('5. Scannez le QR code ou visitez l\'URL pour voir la page de vérification\n');

  // Sauvegarder un fichier HTML de test local
  const htmlPath = path.join(OUTPUT_DIR, 'test-verification.html');
  const html = generateTestHtml(verificationData);
  fs.writeFileSync(htmlPath, html);
  
  console.log(`📄 Page HTML de test créée: ${htmlPath}`);
  console.log('   Ouvrez ce fichier dans un navigateur pour voir un aperçu\n');
  
  console.log('✅ Tout est prêt pour le test !\n');
}

function generateTestHtml(data) {
  return `<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Aperçu - Vérification de Signature</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen py-12 px-4">
  <div class="max-w-4xl mx-auto">
    <div class="text-center mb-8">
      <div class="inline-flex items-center gap-2 bg-white rounded-full px-6 py-2 shadow-md mb-4">
        <svg class="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
        </svg>
        <span class="font-semibold text-slate-900">Odentas Sign</span>
      </div>
      <h1 class="text-4xl font-bold text-slate-900 mb-2">Vérification de Signature</h1>
      <p class="text-slate-600">Certificat de signature électronique</p>
    </div>

    <div class="bg-gradient-to-br from-green-50 to-emerald-50 border-2 border-green-200 rounded-2xl p-8 mb-8">
      <div class="flex items-start gap-4">
        <svg class="w-16 h-16 text-green-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <div>
          <h2 class="text-2xl font-bold text-green-900 mb-2">Signature Techniquement Valide</h2>
          <p class="text-green-700">La signature est techniquement correcte mais utilise un certificat auto-signé non reconnu par les autorités de certification européennes.</p>
        </div>
      </div>
    </div>

    <div class="bg-white rounded-2xl shadow-xl p-8 mb-6">
      <h3 class="text-xl font-bold text-slate-900 mb-4 flex items-center gap-2">
        <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
        </svg>
        Document Signé
      </h3>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
        <div>
          <p class="text-sm text-slate-500 mb-1">Nom du document</p>
          <p class="font-semibold text-slate-900">${data.document_name}</p>
        </div>
        <div>
          <p class="text-sm text-slate-500 mb-1">Signataire</p>
          <p class="font-semibold text-slate-900">${data.signer_name}</p>
        </div>
        <div>
          <p class="text-sm text-slate-500 mb-1">Email</p>
          <p class="font-semibold text-slate-900">${data.signer_email}</p>
        </div>
        <div>
          <p class="text-sm text-slate-500 mb-1">Date de signature</p>
          <p class="font-semibold text-slate-900">${new Date(data.timestamp.timestamp).toLocaleDateString('fr-FR')}</p>
        </div>
      </div>

      <a href="${data.pdf_url}" target="_blank" class="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
        </svg>
        Télécharger le document signé
      </a>
    </div>

    <div class="bg-white rounded-2xl shadow-xl p-8">
      <h3 class="text-xl font-bold text-slate-900 mb-4 flex items-center gap-2">
        <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
        </svg>
        Détails Techniques
      </h3>

      <div class="space-y-3">
        <div class="flex items-center gap-3 p-3 bg-green-50 rounded-lg">
          <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
          </svg>
          <span class="text-green-900 font-medium">Format PAdES-BASELINE-B</span>
        </div>
        <div class="flex items-center gap-3 p-3 bg-green-50 rounded-lg">
          <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
          </svg>
          <span class="text-green-900 font-medium">Algorithme RSASSA-PSS avec SHA-256</span>
        </div>
        <div class="flex items-center gap-3 p-3 bg-green-50 rounded-lg">
          <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
          </svg>
          <span class="text-green-900 font-medium">Intégrité du document vérifiée</span>
        </div>
        <div class="p-3 bg-slate-50 rounded-lg">
          <p class="text-sm font-semibold text-slate-700 mb-1">Hash SHA-256</p>
          <code class="text-xs text-slate-600 break-all">${data.signature_hash}</code>
        </div>
      </div>
    </div>

    <div class="text-center mt-8 text-slate-500 text-sm">
      <p>Odentas Media SAS - Signature électronique conforme PAdES-BASELINE-B</p>
    </div>
  </div>
</body>
</html>`;
}

main().catch(error => {
  console.error('\n❌ ERREUR:', error);
  process.exit(1);
});
