const axios = require('axios');
const cheerio = require('cheerio');
require('dotenv').config();

const OPEN_EXCHANGE_API_KEY = process.env.OPEN_EXCHANGE_API_KEY;

exports.getGSMArenaPrice = async (phoneName, specs = {}) => {
  try {
    // Construct search query with specs if available
    let searchQuery = phoneName;

    const searchUrl = `https://www.gsmarena.com/results.php3?sQuickSearch=yes&sName=${encodeURIComponent(
      searchQuery,
    )}`;
    console.log('Search URL:', searchUrl);

    const searchResponse = await axios.get(searchUrl, {
      headers: {
        'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
      },
    });

    const $search = cheerio.load(searchResponse.data);

    // Try to get first result or probable match
    let firstResultLink = $search('.makers li:first-child a').attr('href');

    if (!firstResultLink) {
      // Check if GSMArena gave probable matches in the makers list
      const probableMatch = $search('.makers li a').first().attr('href');
      if (probableMatch) {
        firstResultLink = probableMatch;
      }
    }

    if (!firstResultLink) {
      throw new Error('No search results or probable matches found');
    }

    // Build the phone page URL
    const phoneUrl = `https://www.gsmarena.com/${firstResultLink}`;
    console.log('Fetching phone page:', phoneUrl);

    const phoneResponse = await axios.get(phoneUrl, {
      headers: {
        'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
      },
    });

    const $phone = cheerio.load(phoneResponse.data);

    // Step 3: Get the price text from the <a> tag
    const priceText = $phone('a[href*="-price-"]').text().trim();
    if (!priceText) throw new Error('Price not found');

    console.log('Raw Price Text:', priceText); // e.g. "$ 799.00 / € 982.75 / £ 691.98 / ₹ 154,900"

    // Step 4: Extract USD price
    const usdMatch = priceText.match(/\$\s?([\d,.]+)/);
    if (!usdMatch) throw new Error('USD price not found');

    const usdPrice = parseFloat(usdMatch[1].replace(/,/g, ''));
    console.log('USD Price:', usdPrice);

    // Step 5: Convert USD to NGN using exchangerate.host
    const rateResponse = await axios.get(
      'https://open.er-api.com/v6/latest/USD',
    );
    const ngnRate = rateResponse.data.rates.NGN;
    const nairaPrice = Math.round(usdPrice * ngnRate);

    return Math.round(nairaPrice);
  } catch (error) {
    console.error(`Error fetching price for ${phoneName}:`, error.message);
    return null;
  }
};

exports.getComputerPrice = async (deviceName) => {
  try {
    const searchUrl = `https://swappa.com/search?q=${encodeURIComponent(
      deviceName,
    )}`;
    const { data } = await axios.get(searchUrl, {
      headers: { 'User-Agent': 'Mozilla/5.0' },
    });

    const $ = cheerio.load(data);

    let priceText = $('.listing_card_price, .price').first().text().trim();
    if (!priceText) {
      throw new Error('Could not find price on Swappa');
    }

    const usdPrice = parseFloat(priceText.replace('$', '').replace(',', ''));

    let fxRate;
    const fxRes = await axios.get('https://open.er-api.com/v6/latest/USD');
    fxRate = fxRes.data.rates.NGN;

    const ngnPrice = Math.round(usdPrice * fxRate);

    return {
      device: deviceName,
      usd_price: usdPrice,
      ngn_price: ngnPrice,
    };
  } catch (err) {
    console.error('Error fetching price:', err.message);
    console.log(err);
    return null;
  }
};
