require('dotenv').config();

async function getMinecraftServers() {
  const endpoint = `${process.env.PANEL_URL}/api/application/servers`;
  
  try {
    const res = await fetch(endpoint, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${process.env.PANEL_APPLICATION_KEY}`,
        'Accept': 'application/json'
      }
    });

    if (!res.ok) throw new Error(`Panel API error: ${res.statusText}`);
    
    const data = await res.json();
    
    // Parse the allowed nest IDs from the environment variable
    const allowedNests = process.env.MINECRAFT_NEST_IDS.split(',').map(id => parseInt(id.trim(), 10));

    // Node ID to friendly name mapping
    const nodeMap = {
      2: 'NC1',
      3: 'TX1'
    };

    return data.data.filter(server => {
      return allowedNests.includes(server.attributes.nest);
    }).map(server => ({
      identifier: server.attributes.identifier,
      name: server.attributes.name,
      nodeId: server.attributes.node,
      node: nodeMap[server.attributes.node] || `Node ${server.attributes.node}`
    }));
  } catch (error) {
    console.error("Discovery failed:", error);
    return [];
  }
}

module.exports = { getMinecraftServers };
