import { defineStore } from 'pinia';
import { ref } from 'vue';
import { verifyToken } from '@/api/admin';

const TOKEN_KEY = 'admin_token';
const USER_KEY = 'admin_user';

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem(TOKEN_KEY) || '');
  const username = ref<string>(localStorage.getItem(USER_KEY) || 'admin');

  function setToken(value: string) {
    token.value = value;
    localStorage.setItem(TOKEN_KEY, value);
  }

  function setUser(value: string) {
    username.value = value;
    localStorage.setItem(USER_KEY, value);
  }

  /** 登录：先用令牌请求 /health 校验有效性，成功后再保存。 */
  async function login(value: string) {
    await verifyToken(value);
    setToken(value);
  }

  function logout() {
    token.value = '';
    localStorage.removeItem(TOKEN_KEY);
  }

  return { token, username, setToken, setUser, login, logout };
});
