import { createContext, useEffect } from 'react';
import { identifyUser } from './trackAnalyticsEvent';
import { User, UserRole, UserTier } from './types';
import useApiFetchedValue from './useApiFetchedValue';

const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL;

export const loadingAccount = {
  id: 0,
  username: 'Loading...',
  role: UserRole.Unknown,
  tier: UserTier.Basic,
} as User;

export const loggedOutAccount = {
  id: 0,
  username: 'Logged Out',
  role: UserRole.LoggedOut,
  tier: UserTier.Basic,
} as User;

const fetchSelfOrRedirect = async () => {
  const res = await (await fetch(`${SERVER_URL}/auth/whoami`, { credentials: 'include' })).json();
  if (typeof res === 'object' && !res.error) {
    return res;
  }
  return loggedOutAccount;
};

const useAccount = () => {
  const [account] = useApiFetchedValue<[], User>(fetchSelfOrRedirect);
  useEffect(() => {
    if (account?.id) {
      identifyUser({ userId: String(account.id), traits: { email: account.email, name: account.username } });
    }
  }, [account]);
  return account || loadingAccount;
};

export const AccountContext = createContext<ReturnType<typeof useAccount>>(undefined as never);

export default useAccount;
