import axios from 'axios';
import ConfigTool from '@/libs/config/ConfigTool';

/**
 * 动态拼接完整URL
 */
const buildUrl = (path) => {
  const config = ConfigTool.load();
  let baseUrl = config.backendUrl || '';
  if (baseUrl.endsWith('/')) {
    baseUrl = baseUrl.slice(0, -1);
  }
  return `${baseUrl}${path}`;
};

/**
 * API模块
 */
export const api = {
  /**
   * 测试API连接
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  test: () => axios.get(buildUrl('/api/test')),

  /**
   * 扫描网络
   * @param {string} subnet 子网地址
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  scan: (subnet) => axios.get(buildUrl('/api/scan_network'), { params: { subnet } }),

  /**
   * 列出所有设备
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  listDevices: () => axios.get(buildUrl('/api/list_devices')),

  /**
   * 解析命令
   * @param {Object} payload
   * @param {string} payload.command - 自然语言命令
   * @param {Array<Object>} payload.devices - 设备列表
   *   每个对象包含 { id: string, ip: string, vendor: string(huawei/cisco/h3c/ruijie/zte) }
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  parseCommand: ({ command, devices }) =>
    axios.post(buildUrl('/api/parse_command'), { command, devices }),

  /**
   * 应用配置
   * @param {string} switch_ip 交换机IP
   * @param {Array<string>} commands 配置命令数组
   * @param username 用户名，无时使用NONE
   * @param password 密码
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  applyConfig: (switch_ip, commands, username, password) =>
    axios.post(buildUrl('/api/execute_cli_commands'), { switch_ip, commands, username, password }),

  /**
   * 获取网络适配器信息
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  getNetworkAdapters: () => axios.get(buildUrl('/api/network_adapters')),

  /**
   * 更新基础URL
   * @param {string} url
   */
  updateBaseUrl: (url) => {
    const config = ConfigTool.load();
    config.backendUrl = url;
    ConfigTool.save(config);
  },
};

/**
 * 获取当前配置
 * @returns {{backendUrl: string, authKey: string}}
 */
export const getConfig = () => ConfigTool.load();

/**
 * 获取基础URL
 * @returns {string}
 */
export const getBaseUrl = () => ConfigTool.load().backendUrl || '';

export default api;
