import React from "react";
import { User } from "./model/User";
import { useStorageState } from "./useStorageState";

const AuthContext = React.createContext<{
  signIn: (user: User) => void;
  signOut: () => void;
  session?: User | null;
  isLoading: boolean;
}>({
  signIn: () => null,
  signOut: () => null,
  session: null,
  isLoading: false,
});

export function useSession() {
  return React.useContext(AuthContext);
}

export function SessionProvider(props: Readonly<React.PropsWithChildren>) {
  const [[isLoading, sessionStr], setSessionStr] = useStorageState("session");

  const session = sessionStr ? User.fromJSON(JSON.parse(sessionStr)) : null;

  return (
    <AuthContext.Provider
      value={{
        signIn: (user: User) => {
          setSessionStr(user.toJSON());
        },
        signOut: () => {
          setSessionStr(null);
        },
        session,
        isLoading,
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
}
