import { defineStore } from 'pinia';
import { ref } from 'vue';
import { adminLogin, type AdminLoginResult } 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) || '');

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

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

  /** 登录：使用管理员账号密码，成功后将返回的 admt_ 令牌保存到本地。 */
  async function login(usernameValue: string, password: string) {
    const result: AdminLoginResult = await adminLogin(usernameValue, password);
    setToken(result.token);
    setUser(result.username);
    return result;
  }

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

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