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

export async function workingTest(req: FastifyRequest, reply: FastifyReply) {
  try {
    console.log('🎯 WORKING TEST - Version corrigée');
    
    const connectionTest = await gravityFormsWorkingService.testConnection();
    
    if (!connectionTest.success) {
      return reply.code(401).send({
        success: false,
        message: "Échec de la connexion",
        error: connectionTest.message,
        debug: {
          base_url: process.env.WP_BASE_URL,
          username: process.env.WP_USERNAME,
          password_length: process.env.WP_APP_PASSWORD?.length
        }
      });
    }

    const forms = await gravityFormsWorkingService.getAllForms();
    
    return reply.code(200).send({
      success: true,
      message: "✅ Connexion réussie avec la version corrigée!",
      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('❌ Working test failed:', error.message);
    
    return reply.code(500).send({
      success: false,
      message: "Erreur lors du test fonctionnel",
      error: error.message,
      debug: {
        base_url: process.env.WP_BASE_URL,
        username: process.env.WP_USERNAME
      }
    });
  }
}

export async function getBusinessPlanWorking(req: FastifyRequest, reply: FastifyReply) {
  try {
    console.log('🔄 Fetching Business Plan data (Working version)...');
    
    const entries = await gravityFormsWorkingService.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 Working 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
    });
  }
}
