import create from 'zustand'

type Environment = 'local' | 'sandbox' | 'production'

const ENV_COOKIE_NAME = 'app_environment'

// Cookie utility functions
const getCookie = (name: string): string | undefined => {
  const cookies = document.cookie.split(';').reduce((acc, cookie) => {
    const [key, value] = cookie.trim().split('=')
    return { ...acc, [key]: value }
  }, {} as Record<string, string>)
  return cookies[name]
}

const setCookie = (name: string, value: string, daysToExpire: number) => {
  const expirationDate = new Date(
    new Date().getTime() + daysToExpire * 24 * 60 * 60 * 1000
  ).toUTCString()
  document.cookie = `${name}=${value}; expires=${expirationDate}; path=/`
}

const getUrlsForEnvironment = (env: Environment) => {
  switch (env) {
    case 'local':
      return {
        apiUrl: import.meta.env.VITE_API_URL_LOCAL,
        workerUrl: import.meta.env.VITE_WORKER_URL_LOCAL,
        privyAppId: import.meta.env.VITE_PRIVY_APP_ID_LOCAL,
      }
    case 'sandbox':
      return {
        apiUrl: import.meta.env.VITE_API_URL_SANDBOX,
        workerUrl: import.meta.env.VITE_WORKER_URL_SANDBOX,
        privyAppId: import.meta.env.VITE_PRIVY_APP_ID_SANDBOX,
      }
    case 'production':
      return {
        apiUrl: import.meta.env.VITE_API_URL_SERVER,
        workerUrl: import.meta.env.VITE_WORKER_URL_SERVER,
        privyAppId: import.meta.env.VITE_PRIVY_APP_ID_PRODUCTION,
      }
  }
}

type ApiStore = {
  environment: Environment
  apiUrl: string
  workerUrl: string
  privyAppId: string
  setEnvironment: (env: Environment) => void
  prepareEnvironmentChange: (env: Environment) => void
}

const getInitialEnvironment = (): Environment => {
  const savedEnv = getCookie(ENV_COOKIE_NAME) as Environment
  return savedEnv || 'sandbox'
}

const initialEnv = getInitialEnvironment()
const initialUrls = getUrlsForEnvironment(initialEnv)

const useApiUrlStore = create<ApiStore>((set) => ({
  environment: initialEnv,
  apiUrl: initialUrls.apiUrl,
  workerUrl: initialUrls.workerUrl,
  privyAppId: initialUrls.privyAppId,
  setEnvironment: (env: Environment) => {
    // Save to cookie with 2 days expiration
    setCookie(ENV_COOKIE_NAME, env, 2)

    const urls = getUrlsForEnvironment(env)
    set({
      environment: env,
      apiUrl: urls.apiUrl,
      workerUrl: urls.workerUrl,
      privyAppId: urls.privyAppId,
    })
  },
  prepareEnvironmentChange: (env: Environment) => {
    // This function will be called from the component where we have access to the Privy hook
    useApiUrlStore.getState().setEnvironment(env)
  },
}))

export default useApiUrlStore
