import { reactive, ref } from "vue";
import { apiRequest } from "../api";

const sshList = ref([]);
const sshLoading = ref(false);
const sshSaving = ref(false);
const sshError = ref("");
const sshEditingName = ref("");
const sshForm = reactive({
  name: "", alias: "", host: "", port: 22,
  username: "", password: "", privateKey: "", passphrase: "",
});

async function loadSSH() {
  sshError.value = "";
  sshLoading.value = true;
  try {
    const res = await apiRequest("/ssh", { method: "GET" });
    sshList.value = Array.isArray(res.data) ? res.data : [];
  } catch (err) {
    sshError.value = err.message || "加载 SSH 配置失败";
  } finally {
    sshLoading.value = false;
  }
}

function resetSSHForm() {
  sshEditingName.value = "";
  Object.assign(sshForm, {
    name: "", alias: "", host: "", port: 22,
    username: "", password: "", privateKey: "", passphrase: "",
  });
}

function editSSH(item) {
  sshEditingName.value = item.name || "";
  Object.assign(sshForm, {
    name: item.name || "", alias: item.alias || "", host: item.host || "",
    port: item.port || 22, username: item.username || "", password: item.password || "",
    privateKey: item.privateKey || "", passphrase: item.passphrase || "",
  });
}

async function saveSSH() {
  sshError.value = "";
  if (!sshForm.alias || !sshForm.host || !sshForm.username) {
    sshError.value = "alias、host 和 username 为必填项";
    return;
  }
  if (!sshEditingName.value && !sshForm.name) {
    sshError.value = "新建配置时 name 为必填项";
    return;
  }
  sshSaving.value = true;
  try {
    const payload = {
      alias: sshForm.alias, host: sshForm.host, port: sshForm.port || 22,
      username: sshForm.username, password: sshForm.password,
      privateKey: sshForm.privateKey, passphrase: sshForm.passphrase,
    };
    if (sshEditingName.value) {
      await apiRequest(`/ssh/${encodeURIComponent(sshEditingName.value)}`, {
        method: "PUT", body: JSON.stringify(payload),
      });
    } else {
      payload.name = sshForm.name;
      await apiRequest("/ssh", { method: "POST", body: JSON.stringify(payload) });
    }
    await loadSSH();
    if (!sshEditingName.value) resetSSHForm();
  } catch (err) {
    sshError.value = err.message || "保存 SSH 配置失败";
  } finally {
    sshSaving.value = false;
  }
}

async function deleteSSH(item) {
  sshError.value = "";
  if (!item.name) return;
  try {
    await apiRequest(`/ssh/${encodeURIComponent(item.name)}`, { method: "DELETE" });
    if (sshEditingName.value === item.name) resetSSHForm();
    await loadSSH();
  } catch (err) {
    sshError.value = err.message || "删除 SSH 配置失败";
  }
}

export function useSSH() {
  return {
    sshList, sshLoading, sshSaving, sshError, sshEditingName, sshForm,
    loadSSH, resetSSHForm, editSSH, saveSSH, deleteSSH,
  };
}
