"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.gravityFormsWorkingService = void 0;
const axios_1 = __importDefault(require("axios"));
const WP_BASE_URL = process.env.WP_BASE_URL || 'https://ccis-agadir.ma';
const WP_USERNAME = process.env.WP_USERNAME || 'ccismsm';
const WP_APP_PASSWORD = process.env.WP_APP_PASSWORD || 'fYh6 mAno bCsk oadI FoU9 MrZw';
class GravityFormsWorkingService {
    constructor() {
        this.baseUrl = WP_BASE_URL;
        // REPRODUCTION EXACTE du curl qui fonctionne
        const credentials = Buffer.from(`${WP_USERNAME}:${WP_APP_PASSWORD}`).toString('base64');
        this.authHeader = `Basic ${credentials}`;
        console.log('🔐 Working Service - Reproduction exacte du curl');
        console.log('Base URL:', this.baseUrl);
        console.log('Username:', WP_USERNAME);
        console.log('Auth Header length:', this.authHeader.length);
    }
    makeRequest(endpoint) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log(`🔗 Making request to: ${this.baseUrl}${endpoint}`);
                // Configuration identique à curl
                const response = yield axios_1.default.get(`${this.baseUrl}${endpoint}`, {
                    headers: {
                        'Authorization': this.authHeader,
                        'Content-Type': 'application/json',
                        'User-Agent': 'curl/7.68.0', // Même User-Agent que curl
                        'Accept': '*/*' // Accept header comme curl
                    },
                    timeout: 30000,
                    // Désactiver la validation du statut pour voir toutes les réponses
                    validateStatus: function (status) {
                        return true; // Accepter tous les status codes
                    }
                });
                console.log(`📊 Response Status: ${response.status} ${response.statusText}`);
                if (response.status === 401) {
                    console.log('❌ Authentication failed - 401 Unauthorized');
                    console.log('Response headers:', response.headers);
                    console.log('Response data:', response.data);
                    throw new Error('Authentication failed - Check application password');
                }
                if (response.status === 403) {
                    console.log('❌ Permission denied - 403 Forbidden');
                    console.log('Response data:', response.data);
                    throw new Error('Permission denied - User may not have required capabilities');
                }
                if (response.status !== 200) {
                    console.log(`⚠️ Unexpected status: ${response.status}`);
                    console.log('Response data:', response.data);
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                console.log(`✅ Request successful: ${endpoint}`);
                return response.data;
            }
            catch (error) {
                // Gestion détaillée des erreurs
                if (error.response) {
                    console.error(`❌ HTTP Error: ${error.response.status}`, {
                        status: error.response.status,
                        statusText: error.response.statusText,
                        data: error.response.data,
                        headers: error.response.headers
                    });
                }
                else if (error.request) {
                    console.error('❌ No response received:', error.request);
                }
                else {
                    console.error('❌ Request setup error:', error.message);
                }
                throw new Error(`API request failed: ${error.message}`);
            }
        });
    }
    testConnection() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log('🧪 Testing WordPress connection (Working version)...');
                const result = yield this.makeRequest('/wp-json/');
                console.log('✅ WordPress connection successful!');
                return {
                    success: true,
                    message: 'Connexion WordPress API réussie',
                    data: {
                        name: result.name,
                        description: result.description,
                        routes: Object.keys(result.routes || {}).length
                    }
                };
            }
            catch (error) {
                console.error('❌ WordPress connection test failed');
                return {
                    success: false,
                    message: error.message
                };
            }
        });
    }
    getAllForms() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log('🔄 Fetching all Gravity Forms (Working version)...');
                const forms = yield this.makeRequest('/wp-json/gf/v2/forms');
                console.log(`✅ Found ${Object.keys(forms).length} forms`);
                // Log des formulaires disponibles
                Object.keys(forms).forEach(formId => {
                    console.log(`   📋 Form ${formId}: ${forms[formId].title}`);
                });
                return forms;
            }
            catch (error) {
                console.error('❌ Failed to fetch forms:', error.message);
                throw error;
            }
        });
    }
    getFormEntries(formId) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log(`🔄 Fetching entries for form ${formId} (Working version)...`);
                // Récupérer les informations du formulaire
                const forms = yield this.getAllForms();
                const form = forms[formId];
                if (!form) {
                    throw new Error(`Formulaire ${formId} non trouvé`);
                }
                // Récupérer les entrées
                const entriesData = yield this.makeRequest(`/wp-json/gf/v2/forms/${formId}/entries`);
                const entries = entriesData.entries || [];
                console.log(`✅ Form ${formId} (${form.title}): ${entries.length} entrées trouvées`);
                // Filtrer et mapper les entrées
                const filteredEntries = [];
                for (const entry of entries) {
                    const spamCheck = this.isSpamEntry(entry);
                    const mappedFields = this.mapFormFields(entry, formId);
                    if (!spamCheck.isSpam) {
                        filteredEntries.push(Object.assign({ id: entry.id, form_id: entry.form_id, form_title: form.title, date_created: entry.date_created, ip: entry.ip, is_legit: true }, mappedFields));
                    }
                }
                console.log(`✅ Form ${formId}: ${filteredEntries.length}/${entries.length} entrées légitimes`);
                return filteredEntries;
            }
            catch (error) {
                console.error(`❌ Error with form ${formId}:`, error.message);
                throw error;
            }
        });
    }
    isSpamEntry(entry) {
        const nom = (entry['1'] || '').toString();
        const email = (entry['6'] || '').toString();
        const userAgent = entry.user_agent || '';
        const spamPatterns = [
            /BTC|Bitcoin|btc/i,
            /graph\.org|http.*graph/i,
            /\ud83d[\udcd7-\udced]|\u2709\ufe0f/i,
            /deal|bonus|transfer|wallet|notification|verification|withdrawal/i,
            /\d+\.\d+ BTC/i
        ];
        for (const pattern of spamPatterns) {
            if (pattern.test(nom) || pattern.test(userAgent)) {
                return { isSpam: true, reason: 'Pattern BTC/Spam détecté' };
            }
        }
        const spamEmails = [
            /boranora\.com|chahcyrans\.com|jagomail\.com|code-gmail\.com|dmxs8\.com|mailgetget\.asia|theking\.id|email-temp\.com|thinhmin\.com/i
        ];
        for (const pattern of spamEmails) {
            if (pattern.test(email)) {
                return { isSpam: true, reason: 'Email spam détecté' };
            }
        }
        return { isSpam: false };
    }
    mapFormFields(entry, formId) {
        const fields = {};
        switch (formId) {
            case '6': // Accompagnement
                fields.nom = entry['1'];
                fields.email = entry['2'];
                fields.telephone = entry['3'];
                fields.projet = entry['4'];
                break;
            case '7': // Business Plan
                fields.nom = entry['1'];
                fields.email = entry['6'];
                fields.telephone = entry['5'];
                fields.projet = entry['7'];
                fields.ville = entry['8'];
                break;
            case '8': // Étude de Marché
                fields.nom = entry['1'];
                fields.email = entry['2'];
                fields.telephone = entry['3'];
                fields.projet = entry['4'];
                break;
            case '9': // Le Networking
                fields.nom = entry['1'];
                fields.email = entry['2'];
                fields.telephone = entry['3'];
                fields.projet = entry['4'];
                break;
            case '10': // Le sourcing
                fields.nom = entry['1'];
                fields.email = entry['2'];
                fields.telephone = entry['3'];
                fields.projet = entry['4'];
                break;
            case '11': // La Prospection
                fields.nom = entry['1'];
                fields.email = entry['2'];
                fields.telephone = entry['3'];
                fields.projet = entry['4'];
                break;
            default:
                fields.nom = entry['1'] || entry['2'] || entry['3'];
                fields.email = entry['6'] || entry['4'] || entry['5'];
                fields.telephone = entry['5'] || entry['3'] || entry['7'];
                fields.projet = entry['7'] || entry['4'] || entry['8'];
                fields.ville = entry['8'] || entry['9'];
        }
        return fields;
    }
}
exports.gravityFormsWorkingService = new GravityFormsWorkingService();
