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

const API_BASE = process.env.YGOPRO_API_BASE;

async function fetchAllSets() {
  try {
    const response = await axios.get(`${API_BASE}/cardsets.php`);
    const sets = response.data.map(s => ({
      set_name: s.set_name,
      set_code: s.set_code,
      num_of_cards: s.num_of_cards || null,
      tcg_date: s.tcg_date || null
    }));
    return sets;
  } catch (err) {
    console.error('Error fetching sets from YGOPRODeck:', err.message);
    throw err;
  }
}

async function fetchAllCards() {
  try {
    const response = await axios.get(`${API_BASE}/cardinfo.php?misc=yes`);
    return response.data.data;
  } catch (err) {
    console.error('Error fetching cards from YGOPRODeck:', err.message);
    throw err;
  }
}

async function fetchDatabaseVersion() {
  const response = await axios.get(`${API_BASE}/checkDBVer.php`);
  const data = response.data;

  // Handle array response from API
  const versionInfo = Array.isArray(data) ? data[0] : data;

  if (!versionInfo || !versionInfo.database_version || !versionInfo.last_update) {
    throw new Error('Invalid database version response from YGOPRODeck API');
  }

  return {
    database_version: versionInfo.database_version,
    last_update: versionInfo.last_update
  };
}


module.exports = { fetchAllCards, fetchAllSets, fetchDatabaseVersion };