/**
 * Pterodactyl Service — power actions and console commands
 * 
 * Uses PANEL_CLIENT_KEY for client endpoints (power, commands).
 * Uses PANEL_APPLICATION_KEY for application endpoints (server listing).
 * Uses PANEL_ADMIN_KEY for admin-level operations.
 *
 * Required .env:
 *   PANEL_URL=https://panel.firefrostgaming.com
 *   PANEL_CLIENT_KEY=ptlc_...
 *   PANEL_APPLICATION_KEY=ptla_...
 *   PANEL_ADMIN_KEY=ptla_...
 */

const PANEL_URL = process.env.PANEL_URL;
const CLIENT_KEY = process.env.PANEL_CLIENT_KEY;
const ADMIN_KEY = process.env.PANEL_ADMIN_KEY || process.env.PANEL_APPLICATION_KEY;

/**
 * Send a power action to a server.
 * @param {string} identifier - Server identifier (short UUID)
 * @param {string} signal - 'start' | 'stop' | 'restart' | 'kill'
 */
async function powerAction(identifier, signal) {
  const valid = ['start', 'stop', 'restart', 'kill'];
  if (!valid.includes(signal)) {
    throw new Error(`Invalid power signal: ${signal}`);
  }

  const url = `${PANEL_URL}/api/client/servers/${identifier}/power`;
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${CLIENT_KEY}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({ signal })
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Power action failed (${res.status}): ${text}`);
  }

  console.log(`[Pterodactyl] ${signal} sent to ${identifier}`);
  return true;
}

/**
 * Send a console command to a running server.
 * @param {string} identifier - Server identifier
 * @param {string} command - Command string (e.g. "say Hello")
 */
async function sendCommand(identifier, command) {
  const url = `${PANEL_URL}/api/client/servers/${identifier}/command`;
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${CLIENT_KEY}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({ command })
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Command failed (${res.status}): ${text}`);
  }

  console.log(`[Pterodactyl] Command sent to ${identifier}: ${command}`);
  return true;
}

/**
 * Get resource usage for a server.
 * Returns: { current_state, memory, cpu, disk }
 * @param {string} identifier - Server identifier
 */
async function getServerResources(identifier) {
  const url = `${PANEL_URL}/api/client/servers/${identifier}/resources`;
  const res = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${CLIENT_KEY}`,
      'Accept': 'application/json'
    }
  });

  if (!res.ok) {
    throw new Error(`Resources fetch failed (${res.status})`);
  }

  const data = await res.json();
  return {
    state: data.attributes.current_state,
    memory: data.attributes.resources.memory_bytes,
    cpu: data.attributes.resources.cpu_absolute,
    disk: data.attributes.resources.disk_bytes
  };
}

module.exports = { powerAction, sendCommand, getServerResources };
