import { OAuthService } from "@/services";
import { OAuthProvider, UseOAuthProps } from "@/types";
import { AuthRequest, AuthSessionResult } from "expo-auth-session";
import { useCallback, useEffect, useState } from "react";
interface UseOAuthCoreProps extends UseOAuthProps {
responseGoogle: AuthSessionResult | null;
requestGoogle: AuthRequest | null;
responseApple: AuthSessionResult | null;
requestApple: AuthRequest | null;
promptAsyncGoogle: () => Promise<AuthSessionResult>;
promptAsyncApple: () => Promise<AuthSessionResult>;
}
export function useOAuthCore({
onSuccess,
onError,
responseGoogle,
requestGoogle,
responseApple,
requestApple,
promptAsyncGoogle,
promptAsyncApple,
}: UseOAuthCoreProps) {
const [isLoading, setIsLoading] = useState(false);
const processAuthResponse = useCallback(
async (
response: AuthSessionResult | null,
request: AuthRequest | null,
provider: OAuthProvider
) => {
setIsLoading(true);
try {
const result = await OAuthService.processAuthResponse(response, request, provider)
if (result.success) {
onSuccess?.(result.success);
} else if (result.error) {
onError?.(result.error);
}
} finally {
setIsLoading(false);
}
},
[onSuccess, onError]
);
// Google OAuth 응답 처리
useEffect(() => {
if (responseGoogle) {
processAuthResponse(responseGoogle, requestGoogle, "google");
}
}, [responseGoogle, requestGoogle, processAuthResponse]);
// Apple OAuth 응답 처리
useEffect(() => {
if (responseApple) {
processAuthResponse(responseApple, requestApple, "apple");
}
}, [responseApple, requestApple, processAuthResponse]);
// 공통 로그인 시작 로직
const startLogin = useCallback(
async (
promptAsync: () => Promise<AuthSessionResult>,
provider: OAuthProvider
) => {
if (isLoading) return;
setIsLoading(true);
const result = await OAuthService.startAuthPrompt(
promptAsync,
provider
);
if (!result.success && result.error) {
onError?.(result.error);
setIsLoading(false);
}
},
[isLoading, onError]
);
const startGoogleLogin = useCallback(
() => startLogin(promptAsyncGoogle, "google"),
[startLogin, promptAsyncGoogle]
);
const startAppleLogin = useCallback(
() => startLogin(promptAsyncApple, "apple"),
[startLogin, promptAsyncApple]
);
return {
isLoading,
startGoogleLogin,
startAppleLogin,
};
}