import axios from "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';

export interface GravityFormEntry {
  id: string;
  form_id: string;
  date_created: string;
  date_updated: string;
  is_starred: string;
  is_read: string;
  ip: string;
  source_url: string;
  user_agent: string;
  currency: string;
  status: string;
  [key: string]: any;
}

export interface FilteredFormEntry {
  id: string;
  form_id: string;
  form_title: string;
  date_created: string;
  nom?: string;
  email?: string;
  telephone?: string;
  projet?: string;
  ville?: string;
  ip: string;
  is_legit: boolean;
  spam_reason?: string;
}

class GravityFormsFinalService {
  private baseUrl: string;
  private authHeader: string;

  constructor() {
    this.baseUrl = WP_BASE_URL;
    
    // IMPORTANT: Utilisation directe du mot de passe avec espaces
    // WordPress Application Password fonctionne avec les espaces dans l'authentification Basic
    const credentials = Buffer.from(`${WP_USERNAME}:${WP_APP_PASSWORD}`).toString('base64');
    this.authHeader = `Basic ${credentials}`;
    
    console.log('🔐 Final Service - Nouveau mot de passe configuré');
    console.log('Base URL:', this.baseUrl);
    console.log('Username:', WP_USERNAME);
    console.log('Password length:', WP_APP_PASSWORD.length);
    console.log('Password (masked):', WP_APP_PASSWORD.substring(0, 4) + '...' + WP_APP_PASSWORD.substring(WP_APP_PASSWORD.length - 4));
  }

  private async makeRequest(endpoint: string): Promise<any> {
    try {
      console.log(`🔗 API Request: ${this.baseUrl}${endpoint}`);
      
      const response = await axios.get(`${this.baseUrl}${endpoint}`, {
        headers: {
          'Authorization': this.authHeader,
          'Content-Type': 'application/json',
          'User-Agent': 'CCIS-Connect-API/1.0',
          'Accept': 'application/json'
        },
        timeout: 30000,
        // Important pour le debug
        transformRequest: [(data, headers) => {
          console.log('📤 Sending headers:', {
            'Authorization': headers['Authorization'] ? 'Present' : 'Missing',
            'Content-Type': headers['Content-Type'],
            'User-Agent': headers['User-Agent']
          });
          return data;
        }]
      });

      console.log(`✅ API Response: ${response.status} ${response.statusText}`);
      return response.data;

    } catch (error: any) {
      console.error(`❌ API Request failed:`, {
        url: `${this.baseUrl}${endpoint}`,
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        headers: error.response?.headers
      });
      
      if (error.response?.status === 401) {
        throw new Error('Authentication failed. Please verify the application password in WordPress.');
      }
      
      throw new Error(`WordPress API Error: ${error.response?.status} - ${error.response?.statusText}`);
    }
  }

  async testConnection(): Promise<{success: boolean; message: string; data?: any}> {
    try {
      console.log('🧪 Testing WordPress API connection...');
      
      const result = await this.makeRequest('/wp-json/');
      
      console.log('✅ WordPress API 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: any) {
      console.error('❌ WordPress API connection failed');
      return {
        success: false,
        message: error.message
      };
    }
  }

  async getAllForms(): Promise<any> {
    try {
      console.log('🔄 Fetching all Gravity Forms...');
      const forms = await 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: any) {
      console.error('❌ Failed to fetch forms:', error.message);
      throw error;
    }
  }

  async getFormEntries(formId: string): Promise<FilteredFormEntry[]> {
    try {
      console.log(`🔄 Fetching entries for form ${formId}...`);
      
      // Récupérer les informations du formulaire
      const forms = await this.getAllForms();
      const form = forms[formId];
      
      if (!form) {
        throw new Error(`Formulaire ${formId} non trouvé`);
      }

      // Récupérer les entrées
      const entriesData = await this.makeRequest(`/wp-json/gf/v2/forms/${formId}/entries`);
      const entries: GravityFormEntry[] = entriesData.entries || [];
      
      console.log(`✅ Form ${formId} (${form.title}): ${entries.length} entrées trouvées`);

      // Filtrer et mapper les entrées
      const filteredEntries: FilteredFormEntry[] = [];
      
      for (const entry of entries) {
        const spamCheck = this.isSpamEntry(entry);
        const mappedFields = this.mapFormFields(entry, formId);
        
        if (!spamCheck.isSpam) {
          filteredEntries.push({
            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: any) {
      console.error(`❌ Error with form ${formId}:`, error.message);
      throw error;
    }
  }

  private isSpamEntry(entry: GravityFormEntry): { isSpam: boolean; reason?: string } {
    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 };
  }

  private mapFormFields(entry: GravityFormEntry, formId: string): Partial<FilteredFormEntry> {
    const fields: Partial<FilteredFormEntry> = {};

    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;
  }
}

export const gravityFormsFinalService = new GravityFormsFinalService();
