import { expoClient } from "@better-auth/expo/client";
import { createAuthClient } from "better-auth/react";
import { genericOAuthClient } from "better-auth/client/plugins";
import * as SecureStore from "expo-secure-store";
import {
  createContext,
  useContext,
  useMemo,
  type ReactNode,
} from "react";

type AuthClient = ReturnType<typeof createAuthClient>;

function createAppAuthClient(apiUrl: string, storagePrefix: string): AuthClient {
  return createAuthClient({
    baseURL: apiUrl,
    plugins: [
          expoClient({
            scheme: "beenvoice",
            storagePrefix,
            storage: SecureStore,
            // Avoid showing a cached session when cookies have already expired.
            disableCache: true,
          }),
      genericOAuthClient(),
    ],
  });
}

const AuthContext = createContext<AuthClient | null>(null);

export function AuthProvider({
  apiUrl,
  storagePrefix,
  children,
}: {
  apiUrl: string;
  storagePrefix: string;
  children: ReactNode;
}) {
  const client = useMemo(
    () => createAppAuthClient(apiUrl, storagePrefix),
    [apiUrl, storagePrefix],
  );

  return <AuthContext.Provider value={client}>{children}</AuthContext.Provider>;
}

export function useAuthClient() {
  const client = useContext(AuthContext);
  if (!client) throw new Error("useAuthClient must be used within AuthProvider");
  return client;
}

export function useSession() {
  return useAuthClient().useSession();
}
