const axios = require('axios');

async function getMarzbanToken(panelUrl, username, password) {
  const url = `${panelUrl}/api/admin/token`;
  const params = new URLSearchParams();
  params.append('username', username);
  params.append('password', password);
  
  const res = await axios.post(url, params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    timeout: 10000
  });
  return res.data.access_token;
}

async function marzbanRequest(panelUrl, token, method, endpoint, data = null) {
  const url = `${panelUrl}/api${endpoint}`;
  const config = {
    method,
    url,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    timeout: 15000
  };
  if (data) config.data = data;
  
  const res = await axios(config);
  return res.data;
}

async function getSystemStats(panelUrl, token) {
  return await marzbanRequest(panelUrl, token, 'GET', '/system');
}

async function getUsers(panelUrl, token, params = {}) {
  const query = new URLSearchParams(params).toString();
  return await marzbanRequest(panelUrl, token, 'GET', `/users?${query}`);
}

async function getUser(panelUrl, token, username) {
  return await marzbanRequest(panelUrl, token, 'GET', `/user/${username}`);
}

async function createUser(panelUrl, token, userData) {
  return await marzbanRequest(panelUrl, token, 'POST', '/user', userData);
}

async function updateUser(panelUrl, token, username, userData) {
  return await marzbanRequest(panelUrl, token, 'PUT', `/user/${username}`, userData);
}

async function deleteUser(panelUrl, token, username) {
  return await marzbanRequest(panelUrl, token, 'DELETE', `/user/${username}`);
}

async function resetUserTraffic(panelUrl, token, username) {
  return await marzbanRequest(panelUrl, token, 'POST', `/user/${username}/reset`);
}

async function getAdminInfo(panelUrl, token) {
  return await marzbanRequest(panelUrl, token, 'GET', '/admin');
}

async function getNodes(panelUrl, token) {
  try {
    return await marzbanRequest(panelUrl, token, 'GET', '/nodes');
  } catch {
    return [];
  }
}

async function getInbounds(panelUrl, token) {
  return await marzbanRequest(panelUrl, token, 'GET', '/inbounds');
}

module.exports = {
  getMarzbanToken,
  getSystemStats,
  getUsers,
  getUser,
  createUser,
  updateUser,
  deleteUser,
  resetUserTraffic,
  getAdminInfo,
  getNodes,
  getInbounds
};
