"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.gravityFormsService = exports.GravityFormsService = void 0;
// src/services/gravity-forms-service.ts
const axios_1 = __importDefault(require("axios"));
const qs_1 = __importDefault(require("qs"));
const crypto_1 = __importDefault(require("crypto"));
const env_1 = require("../utils/env");
class GravityFormsService {
    constructor() {
        const useKeySecret = !!env_1.gfApiKey && !!env_1.gfApiSecret;
        if (useKeySecret) {
            console.log("🔑 Utilisation GF_API_KEY/GF_API_SECRET pour Gravity Forms");
        }
        else {
            console.log("🔑 Utilisation WP_USERNAME/WP_APP_PASSWORD pour Gravity Forms");
        }
        this.client = axios_1.default.create({
            baseURL: `${env_1.wpBaseUrl}/wp-json/gf/v2`,
            timeout: 60000, // 60 secondes
            headers: Object.assign({ "Content-Type": "application/json" }, (useKeySecret
                ? {}
                : {
                    Authorization: "Basic " +
                        Buffer.from(`${env_1.wpUsername}:${env_1.wpAppPassword}`).toString("base64"),
                })),
            paramsSerializer: (params) => qs_1.default.stringify(params, {
                arrayFormat: "indices",
                encode: true,
            }),
        });
        // Intercepteur pour signature HMAC (key/secret)
        if (useKeySecret) {
            this.client.interceptors.request.use((config) => {
                const method = (config.method || "get").toUpperCase();
                const route = config.url || "";
                const expires = Math.floor(Date.now() / 1000) + 60; // 60 secondes
                const stringToSign = `${env_1.gfApiKey}:${method}:${route}:${expires}`;
                const signature = crypto_1.default
                    .createHmac("sha1", env_1.gfApiSecret)
                    .update(stringToSign)
                    .digest("base64");
                config.params = Object.assign(Object.assign({}, (config.params || {})), { api_key: env_1.gfApiKey, signature,
                    expires });
                return config;
            });
        }
    }
    /**
     * Détection simple de spam :
     *  - mots-clés BTC/bitcoin, graph.org, telegra.ph, carrotquest-mail.io, binance
     *  - présence d’emoji dans les textes
     */
    detectSpam(entry) {
        const ignoredKeys = new Set(["id", "form_id", "date_created"]);
        const text = Object.keys(entry)
            .filter((k) => !ignoredKeys.has(k))
            .map((k) => {
            const v = entry[k];
            return typeof v === "string" ? v : JSON.stringify(v);
        })
            .join(" ")
            .toLowerCase();
        // Filtrage basé sur les spams observés (BTC, liens externes)
        const hasBtcKeywords = /btc|bitcoin|graph\.org|telegra\.ph|carrotquest-mail\.io|binance/i.test(text);
        // On ne bloque PAS sur la présence d’émojis, ni sur la langue (arabe, etc.)
        return hasBtcKeywords;
    }
    cleanEntry(entry, formId) {
        const spamFromFields = this.detectSpam(entry);
        const spamFromFlags = !!entry["is_spam"] || !!entry["status_spam"];
        const is_spam = spamFromFields || spamFromFlags;
        const is_legit = !is_spam;
        // Mapping spécifique Business Plan (ID 7)
        if (formId === "7") {
            return {
                id: entry.id,
                form_id: entry.form_id,
                date_created: entry.date_created,
                nom: entry["1"] || entry["nom"] || "",
                prenom: entry["2"] || entry["prenom"] || "",
                nationalite: entry["3"] || entry["nationalite"] || "",
                telephone: entry["4"] || entry["telephone"] || "",
                email: entry["5"] || entry["email"] || "",
                projet: entry["6"] || entry["projet"] || "",
                ville: entry["7"] || entry["ville"] || "",
                formation: entry["8"] || entry["formation"] || "",
                besoins: entry["9"] || entry["besoins"] || "",
                is_legit,
                is_spam,
                status: is_spam ? "spam" : entry["status"] || "active",
                source: "gravity_forms",
            };
        }
        // Fallback générique (autres formulaires 6, 8, 9, 10, 11, etc.)
        return {
            id: entry.id,
            form_id: entry.form_id,
            date_created: entry.date_created,
            is_legit,
            is_spam,
            status: is_spam ? "spam" : entry["status"] || "active",
            source: "gravity_forms",
        };
    }
    getFormEntries(formId) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log(`🔄 Récupération entrées formulaire ${formId}...`);
                const response = yield this.client.get(`/forms/${formId}/entries`, {
                    params: {
                        paging: {
                            page_size: 50,
                            current_page: 1,
                        },
                    },
                });
                const entries = response.data.entries || [];
                console.log(`📊 ${entries.length} entrées brutes récupérées`);
                const cleanedEntries = entries.map((entry) => this.cleanEntry(entry, formId));
                const legitEntries = cleanedEntries.filter((entry) => entry.is_legit);
                console.log(`✅ ${legitEntries.length}/${entries.length} entrées valides après filtrage (sans BTC / emojis)`);
                // On renvoie toutes les entrées, mais les contrôleurs filtrent sur is_legit
                return cleanedEntries;
            }
            catch (error) {
                if (error.code === "ECONNABORTED") {
                    console.error(`⏱️ Timeout Gravity Forms pour le formulaire ${formId}`);
                    throw new Error(`GF_TIMEOUT_FORM_${formId}`);
                }
                console.error(`❌ Erreur récupération entrées ${formId}:`, error.message);
                throw error;
            }
        });
    }
    getAllForms() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log("🔍 Récupération liste des formulaires Gravity Forms...");
                const response = yield this.client.get(`/forms`);
                const forms = response.data || [];
                console.log(`📋 ${Object.keys(forms).length} formulaires récupérés`);
                return forms;
            }
            catch (error) {
                if (error.code === "ECONNABORTED") {
                    console.error("⏱️ Timeout Gravity Forms sur /forms");
                    throw new Error("GF_TIMEOUT_FORMS");
                }
                console.error("❌ Erreur récupération formulaires:", error.message);
                throw error;
            }
        });
    }
}
exports.GravityFormsService = GravityFormsService;
exports.gravityFormsService = new GravityFormsService();
