import { APPLE_CLIENT_ID, OAUTH_CONFIGS } from "@/config";
import { OAuthService } from "@/services/oauth";
import { OAuthProvider } from "@/types";
import { useAuthRequest } from "expo-auth-session";
import { useCallback, useEffect } from "react";
import { UseAppleLoginProps } from "./types";
export function useAppleLogin({
onSuccess,
onError,
isLoading,
setIsLoading,
redirectUri,
}: UseAppleLoginProps) {
// Apple OAuth 설정 (expo-auth-session)
const [requestApple, responseApple, promptAsyncApple] = useAuthRequest(
{
clientId: APPLE_CLIENT_ID,
scopes: OAUTH_CONFIGS[OAuthProvider.APPLE].scopes,
redirectUri,
extraParams: {
access_type: "offline",
prompt: "consent",
},
},
OAUTH_CONFIGS[OAuthProvider.APPLE].discovery,
);
useEffect(() => {
if (!responseApple) return;
OAuthService.processAuthResponse(
responseApple,
requestApple,
OAuthProvider.APPLE,
)
.then((result) => {
if (result.success) onSuccess?.(result.success);
else if (result.error) onError?.(result.error);
})
.finally(() => setIsLoading(false));
}, [responseApple, requestApple, onSuccess, onError, setIsLoading]);
const startAppleLogin = useCallback(async () => {
if (isLoading) return;
setIsLoading(true);
const result = await OAuthService.startAuthPrompt(
promptAsyncApple,
OAuthProvider.APPLE,
);
if (!result.success && result.error) {
onError?.(result.error);
setIsLoading(false);
}
}, [isLoading, onError, promptAsyncApple, setIsLoading]);
return { startAppleLogin };
}