require('dotenv').config();

async function writeWhitelistFile(serverIdentifier, whitelistArray) {
  const endpoint = `${process.env.PANEL_URL}/api/client/servers/${serverIdentifier}/files/write?file=whitelist.json`;
  const res = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.PANEL_CLIENT_KEY}`,
      'Accept': 'application/json',
      'Content-Type': 'text/plain' 
    },
    body: JSON.stringify(whitelistArray, null, 2)
  });
  if (!res.ok) throw new Error(`Failed to write file: ${res.statusText}`);
  return true;
}

async function readServerProperties(serverIdentifier) {
  const endpoint = `${process.env.PANEL_URL}/api/client/servers/${serverIdentifier}/files/contents?file=server.properties`;
  try {
    const res = await fetch(endpoint, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${process.env.PANEL_CLIENT_KEY}`,
        'Accept': 'text/plain'
      }
    });
    
    if (!res.ok) {
        if (res.status === 404) return { exists: false, whitelistEnabled: false, raw: '' };
        throw new Error(`Failed to read properties: ${res.statusText}`);
    }
    
    const content = await res.text();
    // Parse the file for the white-list flag
    const whitelistEnabled = content.includes('white-list=true');
    return { exists: true, whitelistEnabled, raw: content };
  } catch (error) {
    console.error(`Error reading properties for ${serverIdentifier}:`, error);
    return { exists: false, whitelistEnabled: false, raw: '' };
  }
}

module.exports = { writeWhitelistFile, readServerProperties };
