'use client'
import {User} from '@/lib/models'
import {createStore, StoreApi} from 'zustand/vanilla'
import {getProfile} from '@/actions/auth'
import {createContext, useContext, useState} from 'react'
import {useStore} from 'zustand/react'

// store
export type ProfileState = {
  profile: Promise<User | null>
}
export type ProfileActions = {
  refreshProfile: () => void
}
export type ProfileStore = ProfileState & ProfileActions

export function createProfileStore(profile: Promise<User | null>) {
  return createStore<ProfileStore>()(set => ({
    profile,
    refreshProfile: () => {
      set({profile: getProfile().then(resp => resp.success ? resp.data : null)})
    },
  }))
}

// provider
export const ProfileStoreContext = createContext<StoreApi<ProfileStore> | null>(null)

export const ProfileStoreProvider = (props: {
  profile: Promise<User | null>
  children: React.ReactNode
}) => {
  const [store] = useState(() => createProfileStore(props.profile))
  return (
    <ProfileStoreContext.Provider value={store}>
      {props.children}
    </ProfileStoreContext.Provider>
  )
}

// consumer
export function useProfileStore<T>(selector: (state: ProfileStore) => T) {
  const context = useContext(ProfileStoreContext)
  if (!context) {
    throw new Error('ProfileStoreContext 没有正确初始化')
  }
  return useStore(context, selector)
}
