import { ref } from "vue";
import { apiRequest, setToken, clearToken, getToken } from "../api";

const isAuthenticated = ref(false);
const loginPassword = ref("");
const loginError = ref("");
const loginLoading = ref(false);

async function submitLogin() {
  if (!loginPassword.value) return;
  loginLoading.value = true;
  loginError.value = "";
  try {
    const res = await apiRequest("/auth/login", {
      method: "POST",
      body: JSON.stringify({ password: loginPassword.value }),
    });
    setToken(res.data.token);
    isAuthenticated.value = true;
    loginPassword.value = "";
  } catch (e) {
    loginError.value = e.message || "密码错误，请重试";
  } finally {
    loginLoading.value = false;
  }
}

async function checkAuth() {
  const storedToken = getToken();
  if (!storedToken) return;
  try {
    await apiRequest("/auth/verify");
    isAuthenticated.value = true;
  } catch {
    clearToken();
    isAuthenticated.value = false;
  }
}

export function useAuth() {
  return {
    isAuthenticated,
    loginPassword,
    loginError,
    loginLoading,
    submitLogin,
    checkAuth,
  };
}
