import { FastifyReply, FastifyRequest } from "fastify";
import { gravityFormsFinalService } from "../../services/gravity-forms-final";

export async function finalTest(req: FastifyRequest, reply: FastifyReply) {
  try {
    console.log('🎯 FINAL TEST - Nouveau mot de passe');
    
    const connectionTest = await gravityFormsFinalService.testConnection();
    
    if (!connectionTest.success) {
      return reply.code(401).send({
        success: false,
        message: "Échec de la connexion",
        error: connectionTest.message,
        troubleshooting: [
          "Vérifiez que le mot de passe d'application est correctement copié",
          "Vérifiez que l'utilisateur ccismsm a les permissions administrateur",
          "Vérifiez que Gravity Forms est installé et activé"
        ]
      });
    }

    const forms = await gravityFormsFinalService.getAllForms();
    
    return reply.code(200).send({
      success: true,
      message: "✅ Connexion réussie avec le nouveau mot de passe!",
      connection: connectionTest,
      forms: {
        total: Object.keys(forms).length,
        list: Object.keys(forms).map(id => ({
          id,
          title: forms[id].title,
          entries: forms[id].entries || 0
        }))
      }
    });
    
  } catch (error: any) {
    console.error('❌ Final test failed:', error.message);
    
    return reply.code(500).send({
      success: false,
      message: "Erreur lors du test final",
      error: error.message
    });
  }
}

export async function getBusinessPlanFinal(req: FastifyRequest, reply: FastifyReply) {
  try {
    console.log('🔄 Fetching Business Plan data (Final)...');
    
    const entries = await gravityFormsFinalService.getFormEntries('7');
    
    return reply.code(200).send({
      success: true,
      message: "Données Business Plan récupérées avec succès",
      metadata: {
        total_entries: entries.length,
        generated_at: new Date().toISOString()
      },
      entries: entries
    });
    
  } catch (error: any) {
    console.error('❌ Business Plan Final Error:', error.message);
    
    return reply.code(500).send({
      success: false,
      message: "Erreur lors de la récupération des données Business Plan",
      error: error.message
    });
  }
}
