import { userInfoResponseSchema, type SucceedResponse } from '@/schemas';
import { StorageSerializers, useLocalStorage } from '@vueuse/core';
import { pick } from 'lodash-es';
import { defineStore } from 'pinia';
import { reactive, ref } from 'vue';
import { type RouteRecordRaw } from 'vue-router';
import { z } from 'zod';
type SucceedUserInfoResponse = SucceedResponse<z.infer<typeof userInfoResponseSchema>>;
type UserInfo = Pick<SucceedUserInfoResponse['data'], 'id' | 'name' | 'avatar'>;
export const useUserStore = defineStore('user', () => {
  const token = useLocalStorage<string>('token', null, {
    serializer: StorageSerializers.string
  });
  const userInfo = useLocalStorage<UserInfo>('user-info', null, {
    serializer: StorageSerializers.object
  });
  const routeMap = reactive(new Map<string, RouteRecordRaw>());
  const addedRouteSet = reactive(new Set<string>());
  const isInitialized = ref(false);
  function updateUserInfo(userInfoResponse: SucceedUserInfoResponse) {
    userInfo.value = pick(userInfoResponse.data, 'id', 'name', 'avatar');
  }
  function $reset() {
    token.value = null;
    userInfo.value = null;
    routeMap.clear();
    addedRouteSet.clear();
    isInitialized.value = false;
  }
  return { token, userInfo, routeMap, addedRouteSet, isInitialized, updateUserInfo, $reset };
});
