import { OAUTH_CONFIGS } from "@/config";
import { OAuthService, getGoogleClientId } from "@/services/oauth";
import { OAuthProvider } from "@/types";
import { makeRedirectUri, useAuthRequest } from "expo-auth-session";
import Constants from "expo-constants";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useAppleLogin } from "./appleLogin";
import { UseOAuthProps } from "./types";
export const APP_SCHEME = (Constants.expoConfig?.scheme as string) || "ramble";
export function useOAuth({ onSuccess, onError }: UseOAuthProps) {
const [isLoading, setIsLoading] = useState(false);
const redirectUri = useMemo(() => makeRedirectUri({ scheme: APP_SCHEME }), []);
// Google OAuth 설정
const [requestGoogle, responseGoogle, promptAsyncGoogle] = useAuthRequest(
{
clientId: getGoogleClientId(),
scopes: OAUTH_CONFIGS[OAuthProvider.GOOGLE].scopes,
redirectUri,
extraParams: {
access_type: "offline",
prompt: "consent",
},
},
OAUTH_CONFIGS[OAuthProvider.GOOGLE].discovery,
);
// Google OAuth 응답 처리
useEffect(() => {
if (!responseGoogle) return;
OAuthService.processAuthResponse(
responseGoogle,
requestGoogle,
OAuthProvider.GOOGLE,
)
.then((result) => {
if (result.success) onSuccess?.(result.success);
else if (result.error) onError?.(result.error);
})
.finally(() => setIsLoading(false));
}, [responseGoogle, requestGoogle, onSuccess, onError, setIsLoading]);
// Google 로그인 시작 함수
const startGoogleLogin = useCallback(async () => {
if (isLoading) return;
setIsLoading(true);
const result = await OAuthService.startAuthPrompt(
promptAsyncGoogle,
OAuthProvider.GOOGLE,
);
if (!result.success && result.error) {
onError?.(result.error);
setIsLoading(false);
}
}, [isLoading, setIsLoading, onError, promptAsyncGoogle]);
// Apple — 플랫폼별 구현에 위임
const { startAppleLogin } = useAppleLogin({
onSuccess,
onError,
isLoading,
setIsLoading,
redirectUri,
});
return {
isLoading,
startGoogleLogin,
startAppleLogin,
};
}