import { ref, readonly } from 'vue';
import { loginApi } from '../api/login';


const TOKEN_KEY = 'yaoai-h5-access-token';
const storedToken = localStorage.getItem(TOKEN_KEY);

const token = ref<string | null>(storedToken);
const isLoggedIn = ref(!!storedToken);

function saveToken(value: string | null) {
  token.value = value;
  isLoggedIn.value = !!value;
  if (value) {
    localStorage.setItem(TOKEN_KEY, value);
  } else {
    localStorage.removeItem(TOKEN_KEY);
  }
}

function setToken(value: string | null) {
  saveToken(value);
}

function logout() {
  saveToken(null);
}
function login(userinfo: any) {
  return new Promise((resolve, reject) => {
    // loginApi(userinfo).then((res) => {
    //   const { data } = res;
    //   if (data) {
    //     setToken(data)
    //   }
    //   resolve(res)
    // }).catch((err) => {
    //   reject(err)
    // })
    setToken('123')
    resolve({
      data: {
        token: '123'
      }
    })
  })
}

export function useAuth() {
  return {
    token: readonly(token),
    isLoggedIn: readonly(isLoggedIn),
    login,
    setToken,
    logout
  };
}
