/**
 * Paper API client — fetches latest Paper builds and download URLs.
 * Task #101 follow-up — REQ-2026-04-16-vanilla-server-type
 *
 * Paper API v2: https://api.papermc.io/
 * No API key required.
 */

const axios = require('axios');

const BASE = 'https://api.papermc.io/v2';

/**
 * Get available MC versions that Paper supports.
 * Returns array of version strings, newest first.
 */
async function getVersions() {
  const resp = await axios.get(`${BASE}/projects/paper`, { timeout: 10000 });
  return (resp.data.versions || []).reverse();
}

/**
 * Get the latest build number for a given MC version.
 */
async function getLatestBuild(mcVersion) {
  const resp = await axios.get(`${BASE}/projects/paper/versions/${mcVersion}/builds`, { timeout: 10000 });
  const builds = resp.data.builds || [];
  if (builds.length === 0) return null;
  const latest = builds[builds.length - 1];
  return {
    build: latest.build,
    channel: latest.channel,
    downloads: latest.downloads,
    mcVersion
  };
}

/**
 * Get the download URL for a specific Paper build.
 */
function getDownloadUrl(mcVersion, build, fileName) {
  return `${BASE}/projects/paper/versions/${mcVersion}/builds/${build}/downloads/${fileName}`;
}

/**
 * Get the latest Paper jar URL for a MC version.
 * Returns { url, fileName, build } or null.
 */
async function getLatestJarUrl(mcVersion) {
  const latest = await getLatestBuild(mcVersion);
  if (!latest) return null;
  const app = latest.downloads?.application;
  if (!app) return null;
  return {
    url: getDownloadUrl(mcVersion, latest.build, app.name),
    fileName: app.name,
    build: latest.build,
    sha256: app.sha256 || null
  };
}

/**
 * Generate Firefrost default server.properties content.
 * Overrides are merged on top of defaults.
 */
function generateServerProperties(overrides = {}) {
  const defaults = {
    'difficulty': 'easy',
    'gamemode': 'survival',
    'pvp': 'true',
    'hardcore': 'false',
    'spawn-protection': '16',
    'level-type': 'minecraft\\:normal',
    'generate-structures': 'true',
    'level-seed': '',
    'view-distance': '10',
    'simulation-distance': '10',
    'max-players': '20',
    'white-list': 'true',
    'online-mode': 'true',
    'allow-flight': 'false',
    'player-idle-timeout': '0',
    'motd': 'Welcome home, Adventurer. Firefrost Gaming is now open!',
    'server-port': '25565',
    'enable-command-block': 'true',
    'enforce-whitelist': 'true',
    'enable-rcon': 'false',
    'sync-chunk-writes': 'true'
  };

  const merged = { ...defaults, ...overrides };
  const lines = ['# Firefrost Gaming — server.properties', `# Generated by Modpack Installer on ${new Date().toISOString()}`, ''];
  for (const [key, value] of Object.entries(merged)) {
    lines.push(`${key}=${value}`);
  }
  return lines.join('\n');
}

module.exports = { getVersions, getLatestBuild, getLatestJarUrl, getDownloadUrl, generateServerProperties };
