import { STORE_KEY } from '@utils/enum'
import { Helpers } from '@utils/helper'
import { createContext, onMount, useContext } from 'solid-js'
import { createStore, produce } from 'solid-js/store'

export const SiteContext = createContext()

export function SiteContextProvider(props) {
  const [store, setStore] = createStore({
    auth: false,
    userInfo: null,
  })

  onMount(() => {
    const storeData = Helpers.decrypt(localStorage.getItem(STORE_KEY))
    if (!storeData) return
    setStore(storeData)
  })

  const setLocalStore = () => {
    if (store.auth) {
      localStorage.setItem(STORE_KEY, Helpers.encrypt(store))
    } else {
      localStorage.removeItem(STORE_KEY)
    }
  }

  const setAuth = ({ auth, user }) => {
    setStore(
      produce((s) => {
        s.auth = auth
        s.userInfo = user
      }),
    )
    setLocalStore()
  }

  const setUser = (user) => {
    setStore('userInfo', user)
    setLocalStore()
  }

  return (
    <SiteContext.Provider value={{ store, setAuth, setUser }}>
      {props.children}
    </SiteContext.Provider>
  )
}

export function useSiteContext() {
  return useContext(SiteContext)
}
