import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import axios from 'axios';

interface ServerConfig {
  id: string;
  name: string;
  url: string;
  isDefault?: boolean;
}

const STORAGE_KEY = 'server_configs';
const CURRENT_SERVER_KEY = 'current_server';

export const useServerStore = defineStore('server', () => {
  const servers = ref<ServerConfig[]>([]);
  const currentServerId = ref<string | null>(null);
  const connectionStatus = ref<'connected' | 'disconnected' | 'checking'>('disconnected');

  const currentServer = computed(() => 
    servers.value.find(s => s.id === currentServerId.value)
  );

  const isConfigured = computed(() => !!currentServer.value);

  // 加载配置
  function loadConfig() {
    const savedServers = localStorage.getItem(STORAGE_KEY);
    const savedCurrent = localStorage.getItem(CURRENT_SERVER_KEY);
    
    if (savedServers) {
      servers.value = JSON.parse(savedServers);
    }
    if (savedCurrent) {
      currentServerId.value = savedCurrent;
    }
  }

  // 保存配置
  function saveConfig() {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(servers.value));
    if (currentServerId.value) {
      localStorage.setItem(CURRENT_SERVER_KEY, currentServerId.value);
    }
  }

  // 添加服务器
  function addServer(config: Omit<ServerConfig, 'id'>) {
    const id = `server_${Date.now()}`;
    const server: ServerConfig = { ...config, id };
    servers.value.push(server);
    
    if (servers.value.length === 1 || config.isDefault) {
      currentServerId.value = id;
    }
    
    saveConfig();
    return server;
  }

  // 更新服务器
  function updateServer(id: string, config: Partial<ServerConfig>) {
    const index = servers.value.findIndex(s => s.id === id);
    if (index !== -1) {
      servers.value[index] = { ...servers.value[index], ...config };
      saveConfig();
    }
  }

  // 删除服务器
  function removeServer(id: string) {
    const index = servers.value.findIndex(s => s.id === id);
    if (index !== -1) {
      servers.value.splice(index, 1);
      if (currentServerId.value === id) {
        currentServerId.value = servers.value[0]?.id || null;
      }
      saveConfig();
    }
  }

  // 切换当前服务器
  function setCurrentServer(id: string) {
    if (servers.value.find(s => s.id === id)) {
      currentServerId.value = id;
      saveConfig();
    }
  }

  // 检查服务器连接
  async function checkConnection(url?: string): Promise<boolean> {
    const targetUrl = url || currentServer.value?.url;
    if (!targetUrl) return false;

    connectionStatus.value = 'checking';
    try {
      const response = await axios.get(`${targetUrl}/api/health`, { timeout: 5000 });
      connectionStatus.value = response.data?.status === 'ok' ? 'connected' : 'disconnected';
      return connectionStatus.value === 'connected';
    } catch {
      connectionStatus.value = 'disconnected';
      return false;
    }
  }

  return {
    servers,
    currentServer,
    currentServerId,
    connectionStatus,
    isConfigured,
    loadConfig,
    addServer,
    updateServer,
    removeServer,
    setCurrentServer,
    checkConnection,
  };
});
