// src/services/wpGravityForms.ts
import axios from "axios";

const WP_BASE_URL = process.env.WP_BASE_URL || "";
const GF_API_KEY = process.env.GF_API_KEY || "";
const GF_API_SECRET = process.env.GF_API_SECRET || "";

// Construit une URL complète à partir de WP_BASE_URL
function buildWpUrl(path: string) {
  return WP_BASE_URL.replace(/\/$/, "") + path;
}

/**
 * Récupère la liste des formulaires Gravity Forms
 * GET /wp-json/gf/v2/forms
 */
export async function fetchFormsList() {
  const url = buildWpUrl("/wp-json/gf/v2/forms");

  try {
    // Première version : SANS auth car votre curl fonctionne déjà sans authentification.
    const res = await axios.get(url, {
      timeout: 15000,
    });

    return res.data; // objet { "6": {...}, "7": {...}, ... }
  } catch (error: any) {
    console.error("❌ Erreur Gravity Forms LISTE:", {
      status: error.response?.status,
      data: error.response?.data,
      url,
    });
    throw new Error(
      `API Gravity Forms (forms list) : ${error.response?.status || ""}`
    );
  }
}

/**
 * Récupère les entrées d’un formulaire donné
 * GET /wp-json/gf/v2/forms/{formId}/entries
 */
export async function fetchFormEntries(formId: number | string) {
  const url = buildWpUrl(`/wp-json/gf/v2/forms/${formId}/entries`);

  try {
    // Ici, vous pouvez garder l’auth si nécessaire.
    const res = await axios.get(url, {
      auth: {
        username: GF_API_KEY,
        password: GF_API_SECRET,
      },
      params: {
        page_size: 100,
      },
      timeout: 20000,
    });

    return res.data; // { total_count, entries: [...] }
  } catch (error: any) {
    console.error("❌ Erreur Gravity Forms ENTRIES:", {
      status: error.response?.status,
      data: error.response?.data,
      url,
    });
    throw new Error(
      `API Gravity Forms (entries form ${formId}) : ${
        error.response?.status || ""
      }`
    );
  }
}

/**
 * Récupère les entrées du formulaire Business Plan (id = 7)
 */
export async function fetchBusinessPlanEntries() {
  const BUSINESS_PLAN_FORM_ID = 7;
  return fetchFormEntries(BUSINESS_PLAN_FORM_ID);
}
