const axios = require('axios');
const settings = require('../config/settings.json');

// Base URL for the Pamsika API
const API_BASE_URL = settings.apiBaseUrl;

/**
 * Get all products/events
 * @returns {Promise<Array>} Array of products
 */
async function getAllProducts() {
  try {
    // Get all products from API
    const response = await axios.get(`${API_BASE_URL}/products/all`);
    console.log('API response for products:', JSON.stringify(response.data, null, 2));
    
    // Filter for active tickets only
    const activeTickets = response.data.filter(product => 
      product.product_status === 'active' && 
      product.product_category_name === 'Tickets'
    );
    console.log('Filtered active tickets:', JSON.stringify(activeTickets, null, 2));
    return activeTickets;
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error('Error fetching all products:', errorMessage);
    throw new Error(errorMessage);
  }
}

/**
 * Get a specific product by ID
 * @param {string} productId - The ID of the product
 * @returns {Promise<Object>} Product details
 */
async function getProductById(productId) {
  try {
    const response = await axios.get(`${API_BASE_URL}/products/${productId}`);
    console.log('API response for product:', JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error(`Error fetching product ${productId}:`, errorMessage);
    throw new Error(errorMessage);
  }
}

/**
 * Search for products with optional filters
 * @param {string} query - Search query string
 * @param {string} priceRange - Optional price range (e.g., "100-500")
 * @param {string} sortOption - Optional sorting option (e.g., "Newest", "PLowToHigh")
 * @returns {Promise<Array>} Array of matching products
 */
async function searchProducts(query, priceRange = null, sortOption = null) {
  try {
    let url = `${API_BASE_URL}/products/search/${query}`;
    
    // Add optional query parameters if provided
    const params = new URLSearchParams();
    if (priceRange) params.append('product_price_range', priceRange);
    if (sortOption) params.append('product_page_filter', sortOption);
    
    if (params.toString()) {
      url += `?${params.toString()}`;
    }
    
    const response = await axios.get(url);
    console.log('API response for search:', JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error('Error searching products:', errorMessage);
    throw new Error(errorMessage);
  }
}

/**
 * Initiate a 'Buy Now' checkout process
 * @param {string} phone - Customer's phone number
 * @param {string} fullname - Customer's full name
 * @param {Object} cart - Cart object with product IDs and quantities
 * @param {number} amount - Total amount to bill
 * @returns {Promise<Object>} Order details
 */
async function buyNow(phone, fullname, cart, amount) {
  try {
    const payload = {
      phone,
      fullname,
      buy_now_cart: cart,
      amount
    };
    
    console.log('API payload for buy now:', JSON.stringify(payload, null, 2));
    const response = await axios.post(`${API_BASE_URL}/buy-item-now`, payload);
    console.log('API response for buy now:', JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error('Error processing buy now request:', errorMessage);
    throw new Error(errorMessage);
  }
}

/**
* Get order details by order ID
 * @param {string} orderId - The ID of the order
 * @returns {Promise<Array>} Array of order details
 */
async function getOrderDetails(orderId) {
  try {
    const response = await axios.get(`${API_BASE_URL}/order-details/${orderId}`);
    console.log('API response for order details:', JSON.stringify(response.data, null, 2));
    return Array.isArray(response.data) ? response.data : [];
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error(`Error fetching order ${orderId}:`, errorMessage);
    throw new Error(errorMessage);
  }
}

/**
* Get product price by product price ID
 * @param {string} productPriceId - The ID of the product price
 * @returns {Promise<Object>} Product price details
 */
async function getProductPriceById(productPriceId) {
  try {
    // We need to get all product prices and filter for the specific ID
    // This is because the API doesn't have a direct endpoint for product price by ID
    // We'll need to get all products and then all their prices to find the matching one
    const products = await getAllProducts();
    
    for (const product of products) {
      try {
        const prices = await getProductPrices(product.product_id);
        const matchingPrice = prices.find(price => price.product_price_id === productPriceId);
        if (matchingPrice) {
          return {
            ...matchingPrice,
            product_name: product.product_name
          };
        }
      } catch (error) {
        // Continue to next product if this one fails
        console.error(`Error fetching prices for product ${product.product_id}:`, error);
      }
    }
    
    throw new Error(`Product price with ID ${productPriceId} not found`);
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error(`Error fetching product price ${productPriceId}:`, errorMessage);
    throw new Error(errorMessage);
  }
}

/**
 * Get product prices by product ID
 * @param {string} productId - The ID of the product
 * @returns {Promise<Array>} Array of product prices
 */
async function getProductPrices(productId) {
  try {
    const response = await axios.get(`${API_BASE_URL}/products/product-prices/${productId}`);
    console.log('API response for product prices:', JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    const errorMessage = error.response
      ? `API error: ${error.response.status} - ${error.response.data.message || 'Unknown error'}`
      : `Network error: ${error.message}`;
    console.error(`Error fetching product prices for ${productId}:`, errorMessage);
    throw new Error(errorMessage);
  }
}

module.exports = {
  getAllProducts,
  getProductById,
  searchProducts,
  buyNow,
  getOrderDetails,
  getProductPrices,
  getProductPriceById
};