/**
 * Session management such as
 * - getUserToken
 * - setUserToken
 *
 */
import { setHttpToken } from "@racletteCore/lib/httpClient"
import { getCookie } from "@racletteCore/lib/dataHelper"
import log from "../lib/logger"
// TODO use this file in the files we currently do authentication in instead of the inline code in ie main.ts
const AUTH_TOKEN_KEY = "authToken"

const getUserToken = () => {
  const token = getCookie(AUTH_TOKEN_KEY)

  return token
}

const setUserToken = (api, socket, token) => {
  document.cookie = `${AUTH_TOKEN_KEY}=${token}; Secure; SameSite=Lax; max-age=86400; Path=/`
  // set token in http client
  setHttpToken(token)
}

const checkUserToken = async (api, socket, store) => {
  const token = getUserToken()

  if (!token) {
    return false
  }
  // set token in client
  setUserToken(api, socket, token)
  // check if token is valid
  try {
    const user = await api.get("/core/user/check-token")

    // early return if no result
    if (!user || user.data === "") {
      return false
    }
    // save received user object to store
    store.dispatch({ type: "user/set", payload: user.data })

    return user
  } catch (e) {
    log.api("sessionHandler/checkUserToken", e?.response?.data)

    return false
  }
}

export { getUserToken, setUserToken, checkUserToken, AUTH_TOKEN_KEY }
