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 || 'Pkil wzVo stXl Fd2Q ejRY Nvae';

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 GravityFormsServiceCorrected {
  private baseUrl: string;
  private authHeader: string;

  constructor() {
    this.baseUrl = WP_BASE_URL;
    
    // Nettoyage du mot de passe - suppression des espaces superflus
    const cleanPassword = WP_APP_PASSWORD.trim();
    const credentials = Buffer.from(`${WP_USERNAME}:${cleanPassword}`).toString('base64');
    this.authHeader = `Basic ${credentials}`;
    
    console.log('🔐 Corrected Auth Service initialized');
    console.log('Base URL:', this.baseUrl);
    console.log('Username:', WP_USERNAME);
    console.log('Password cleaned, length:', cleanPassword.length);
  }

  private async makeRequest(endpoint: string): Promise<any> {
    try {
      console.log(`🔗 Making request to: ${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,
        validateStatus: function (status) {
          return status < 500; // Resolve only if status code < 500
        }
      });

      if (response.status === 401) {
        throw new Error(`Authentication failed - Check application password`);
      }

      if (response.status === 403) {
        throw new Error(`Permission denied - User may not have required capabilities`);
      }

      if (response.status !== 200) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      console.log(`✅ Request successful: ${endpoint}`);
      return response.data;

    } catch (error: any) {
      console.error(`❌ Request failed for ${endpoint}:`, {
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        message: error.message
      });
      
      throw new Error(
        error.response?.data?.message || 
        error.message || 
        `API request failed for ${endpoint}`
      );
    }
  }

  async testConnection(): Promise<any> {
    try {
      console.log('🧪 Testing WordPress connection...');
      const result = await this.makeRequest('/wp-json/');
      console.log('✅ WordPress connection successful');
      return result;
    } catch (error: any) {
      console.error('❌ WordPress connection test failed');
      throw error;
    }
  }

  async getAllForms(): Promise<any> {
    try {
      console.log('🔄 Fetching all forms...');
      const forms = await this.makeRequest('/wp-json/gf/v2/forms');
      console.log(`✅ Found ${Object.keys(forms).length} forms`);
      return forms;
    } catch (error: any) {
      console.error('❌ Failed to fetch forms');
      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(`Form ${formId} not found`);
      }

      // 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}: ${entries.length} entries found`);

      // Filtrer et mapper les entrées
      return entries.map(entry => this.filterAndMapEntry(entry, form.title));
      
    } catch (error: any) {
      console.error(`❌ Error with form ${formId}:`, error.message);
      throw error;
    }
  }

  private filterAndMapEntry(entry: GravityFormEntry, formTitle: string): FilteredFormEntry {
    const spamCheck = this.isSpamEntry(entry);
    const mappedFields = this.mapFormFields(entry);

    return {
      id: entry.id,
      form_id: entry.form_id,
      form_title: formTitle,
      date_created: entry.date_created,
      ip: entry.ip,
      is_legit: !spamCheck.isSpam,
      spam_reason: spamCheck.isSpam ? spamCheck.reason : undefined,
      ...mappedFields
    };
  }

  private isSpamEntry(entry: GravityFormEntry): { isSpam: boolean; reason?: string } {
    // Votre logique de détection de spam existante
    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): Partial<FilteredFormEntry> {
    const fields: Partial<FilteredFormEntry> = {};
    const formId = entry.form_id.toString();

    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;
      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 gravityFormsServiceCorrected = new GravityFormsServiceCorrected();
