import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getUserProfile } from '@/api/user/auth';

interface UserInfo {
  id: number;
  phone: string;
  nickname: string;
  avatar: string;
  role: string;
}

export const useUserStore = defineStore('user', () => {
  const token = ref(uni.getStorageSync('token') || '');
  const userInfo = ref<UserInfo | null>(uni.getStorageSync('userInfo') || null);

  function setLogin(data: { accessToken: string; userInfo: UserInfo }) {
    token.value = data.accessToken;
    userInfo.value = data.userInfo;
    uni.setStorageSync('token', data.accessToken);
    uni.setStorageSync('userInfo', data.userInfo);
  }

  function logout() {
    token.value = '';
    userInfo.value = null;
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
    uni.reLaunch({ url: '/pages/login/index' });
  }

  function isLoggedIn() {
    return !!token.value;
  }

  async function fetchUserInfo() {
    if (!token.value) return;
    try {
      const res = await getUserProfile();
      if (res.code === 200) {
        userInfo.value = res.data;
        uni.setStorageSync('userInfo', res.data);
      }
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
  }

  return { token, userInfo, setLogin, logout, isLoggedIn, fetchUserInfo };
});
