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 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 text 文本
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  parseCommand: (text) => axios.post(buildUrl('/api/parse_command'), { command: text }),

  /**
   * 应用配置
   * @param switch_ip 交换机ip
   * @param config 配置
   * @returns {Promise<axios.AxiosResponse<any>>}
   */
  applyConfig: (switch_ip, config) =>
    axios.post(buildUrl('/api/apply_config'), { switch_ip, config }),

  /**
   * 更新基础URL
   * @param 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|string}
 */
export const getBaseUrl = () => ConfigTool.load().backendUrl || '';

export default api;
