/**
 * OwletService.js
 * Handles all Owlet SMM API integration with intelligent filtering
 * Automatically excludes ALL services containing "views" and "free" keywords
 */

const axios = require('axios');

class OwletService {
  constructor() {
    this.apiUrl = process.env.OWLET_API_URL || 'https://the-owlet.com/api/v2';
    this.apiKey = process.env.OWLET_API_KEY;
    this.timeout = 60000; // 60 seconds
    this.cache = {};
    this.cacheExpiry = 3600000; // 1 hour
  }

  /**
   * Create axios client for Owlet API
   */
  createClient() {
    return axios.create({
      baseURL: this.apiUrl,
      timeout: this.timeout,
      headers: {
        'Content-Type': 'application/json',
      }
    });
  }

  /**
   * Get raw services from Owlet API (cached)
   */
  async getServices() {
    try {
      // Check cache first
      if (this.cache['raw_services'] && Date.now() - this.cache['raw_services'].time < this.cacheExpiry) {
        console.log('[OwletService] Returning cached services');
        return this.cache['raw_services'].data;
      }

      console.log('[OwletService] Fetching services from Owlet API...');
      const client = this.createClient();

      const response = await client.post('/', null, {
        params: {
          key: this.apiKey,
          action: 'services',
        }
      });

      if (response.data.error) {
        throw new Error(response.data.error);
      }

      // Handle both array and object responses
      const services = Array.isArray(response.data) ? response.data : Object.values(response.data);

      console.log(`[OwletService] Retrieved ${services.length} total services from API`);

      // Cache the result
      this.cache['raw_services'] = {
        data: services,
        time: Date.now()
      };

      return services;
    } catch (error) {
      console.error('[OwletService] Get services failed:', error.message);
      return [];
    }
  }

  /**
   * Determine if service should be included (CRITICAL FILTERING)
   * Returns FALSE if service contains "view" or "free" keywords
   */
  shouldIncludeService(service) {
    const name = (service.name || '').toLowerCase();
    const category = (service.category || '').toLowerCase();
    const rate = parseFloat(service.rate || 0);

    // RULE 1: Exclude if rate is 0 or very low (free services)
    if (rate < 0.01) {
      console.debug(`[OwletService] Excluding free service: ${service.name} (rate: ${rate})`);
      return false;
    }

    // RULE 2: Exclude if contains "view" or "views" keywords (case-insensitive)
    const viewKeywords = [
      'view',
      'views',
      'video view',
      'story view',
      'reel view',
      'post view',
      'profile view',
      'impression',
      'impressions',
      'reach',
    ];

    for (const keyword of viewKeywords) {
      if (name.includes(keyword) || category.includes(keyword)) {
        console.debug(`[OwletService] Excluding views service: ${service.name} (keyword: ${keyword})`);
        return false;
      }
    }

    // RULE 3: Exclude if contains "free" keywords
    const freeKeywords = [
      'free',
      '99.99% free',
      '99.9% free',
      'free service',
      '0.00',
      'gratis',
      'complimentary',
    ];

    for (const keyword of freeKeywords) {
      if (name.includes(keyword) || category.includes(keyword)) {
        console.debug(`[OwletService] Excluding free keyword service: ${service.name} (keyword: ${keyword})`);
        return false;
      }
    }

    // Service passed all filters
    return true;
  }

  /**
   * Get ALL services with intelligent filtering
   * Excludes: ALL "views" services and ALL "free" services
   */
  async getFilteredServices() {
    try {
      const allServices = await this.getServices();

      if (!allServices || allServices.length === 0) {
        console.warn('[OwletService] No services retrieved from Owlet API');
        return [];
      }

      const filtered = allServices.filter(service => this.shouldIncludeService(service));

      console.log(`[OwletService] Filter Results:
        - Total Retrieved: ${allServices.length}
        - After Filtering: ${filtered.length}
        - Excluded: ${allServices.length - filtered.length}
      `);

      return filtered;
    } catch (error) {
      console.error('[OwletService] Filter failed:', error.message);
      return [];
    }
  }

  /**
   * Get services grouped by category with counts
   */
  async getServicesByCategory() {
    try {
      const services = await this.getFilteredServices();
      const grouped = {};

      for (const service of services) {
        const category = service.category || 'Uncategorized';

        if (!grouped[category]) {
          grouped[category] = {
            name: category,
            icon: this.getCategoryIcon(category),
            services: [],
            count: 0
          };
        }

        grouped[category].services.push(service);
        grouped[category].count++;
      }

      // Sort by category name
      const sorted = Object.keys(grouped)
        .sort()
        .reduce((result, key) => {
          result[key] = grouped[key];
          return result;
        }, {});

      console.log(`[OwletService] Grouped into ${Object.keys(sorted).length} categories`);
      return sorted;
    } catch (error) {
      console.error('[OwletService] Category grouping failed:', error.message);
      return {};
    }
  }

  /**
   * Get category icon based on keywords
   */
  getCategoryIcon(categoryName) {
    const name = (categoryName || '').toLowerCase();

    const iconMap = {
      'instagram': 'fab fa-instagram',
      'facebook': 'fab fa-facebook-f',
      'youtube': 'fab fa-youtube',
      'tiktok': 'fab fa-tiktok',
      'twitter': 'fab fa-twitter',
      'telegram': 'fab fa-telegram',
      'spotify': 'fab fa-spotify',
      'soundcloud': 'fab fa-soundcloud',
      'linkedin': 'fab fa-linkedin-in',
      'pinterest': 'fab fa-pinterest',
      'snapchat': 'fab fa-snapchat',
      'discord': 'fab fa-discord',
      'reddit': 'fab fa-reddit',
      'threads': 'fas fa-comments',
      'whatsapp': 'fab fa-whatsapp',
      'audiomack': 'fas fa-music',
      'boomplay': 'fas fa-music',
      'apple music': 'fab fa-apple',
      'itunes': 'fab fa-itunes-note',
      'nigerian': 'fas fa-flag',
      'cheap': 'fas fa-tags',
      'exclusive': 'fas fa-star',
      'premium': 'fas fa-crown',
    };

    for (const [keyword, icon] of Object.entries(iconMap)) {
      if (name.includes(keyword)) {
        return icon;
      }
    }

    return 'fas fa-th'; // Default icon
  }

  /**
   * Place order with Owlet
   */
  async placeOrder(serviceId, link, quantity) {
    try {
      const client = this.createClient();

      const response = await client.post('/', null, {
        params: {
          key: this.apiKey,
          action: 'add',
          service: serviceId,
          link: link,
          quantity: quantity,
        }
      });

      if (response.data.error) {
        throw new Error(response.data.error);
      }

      return {
        success: true,
        orderId: response.data.order,
        charge: response.data.charge,
        startCount: response.data.start_count
      };
    } catch (error) {
      console.error('[OwletService] Order placement failed:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Get order status from Owlet API
   */
  async getOrderStatus(orderId) {
    try {
      const client = this.createClient();

      const response = await client.post('/', null, {
        params: {
          key: this.apiKey,
          action: 'status',
          order: orderId,
        }
      });

      if (response.data.error) {
        throw new Error(response.data.error);
      }

      return {
        success: true,
        status: response.data.status,
        charge: response.data.charge,
        startCount: response.data.start_count,
        remains: response.data.remains
      };
    } catch (error) {
      console.error('[OwletService] Status check failed:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Get multiple order statuses
   */
  async getMultipleOrderStatus(orderIds) {
    try {
      const client = this.createClient();

      const response = await client.post('/', null, {
        params: {
          key: this.apiKey,
          action: 'status',
          orders: orderIds.join(','),
        }
      });

      if (response.data.error) {
        throw new Error(response.data.error);
      }

      return {
        success: true,
        statuses: response.data
      };
    } catch (error) {
      console.error('[OwletService] Multi-status check failed:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Refund an order with Owlet API
   */
  async refundOrder(orderId) {
    try {
      const client = this.createClient();

      const response = await client.post('/', null, {
        params: {
          key: this.apiKey,
          action: 'refund',
          order: orderId,
        }
      });

      if (response.data.error) {
        throw new Error(response.data.error);
      }

      return {
        success: true,
        message: response.data.message || 'Order refunded successfully'
      };
    } catch (error) {
      console.error('[OwletService] Refund failed:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Get account balance from Owlet
   */
  async getBalance() {
    try {
      const client = this.createClient();

      const response = await client.post('/', null, {
        params: {
          key: this.apiKey,
          action: 'balance',
        }
      });

      if (response.data.error) {
        throw new Error(response.data.error);
      }

      return {
        success: true,
        balance: response.data.balance,
        currency: response.data.currency || 'USD'
      };
    } catch (error) {
      console.error('[OwletService] Balance check failed:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Test API connection
   */
  async testConnection() {
    try {
      console.log('[OwletService] Testing Owlet API connection...');

      const result = await this.getBalance();

      if (result.success) {
        console.log(`[OwletService] ✅ Connection successful! Balance: ${result.balance} ${result.currency}`);
      } else {
        console.error(`[OwletService] ❌ Connection failed: ${result.error}`);
      }

      return result;
    } catch (error) {
      console.error('[OwletService] Connection test error:', error.message);
      return {
        success: false,
        error: error.message,
        message: 'Connection failed'
      };
    }
  }

  /**
   * Clear cache
   */
  clearCache() {
    this.cache = {};
    console.log('[OwletService] Cache cleared');
  }
}

module.exports = new OwletService();
