bu kod amatörce yazıldı daha iyi hale getir

enum AppleErrorCodes {
  CANCELED = "ERR_REQUEST_CANCELED",
  FAILED = "ERR_REQUEST_FAILED",
  NOT_HANDLED = "ERR_REQUEST_NOT_HANDLED",
  NOT_INTERACTIVE = "ERR_REQUEST_NOT_INTERACTIVE",
}


//
// Error codes
// Most of the error codes match the official Apple Authorization errors.
//
//     Code	Description
// ERR_INVALID_OPERATION	An invalid authorization operation has been performed.
//     ERR_INVALID_RESPONSE	The authorization request received an invalid response.
//     ERR_INVALID_SCOPE	An invalid AppleAuthenticationScope was passed in.
// ERR_REQUEST_CANCELED	The user canceled the authorization attempt.
//     ERR_REQUEST_FAILED	The authorization attempt failed. See the error message for additional information.
//     ERR_REQUEST_NOT_HANDLED	The authorization request wasn't correctly handled.
// ERR_REQUEST_NOT_INTERACTIVE	The authorization request isn't interactive.
// ERR_REQUEST_UNKNOWN	The authorization attempt failed for an unknown reason.
// Previous (Expo SDK)
//
// Accelerometer
//
// Next (Expo SDK)
//
// Application
import CONFIG from "@/core/CONFIG";
import axios from "axios";
import IconButton from "@/components/SigninButtons/IconButton";
import { useRouter } from "expo-router";
import { useSession } from "@/core/session/AuthContext";
import * as AppleAuthentication from "expo-apple-authentication";

async function appleSignInRequest2(): Promise<AppleSignInResponse | undefined> {
  const credential = await AppleAuthentication.signInAsync({
    requestedScopes: [
      AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
      AppleAuthentication.AppleAuthenticationScope.EMAIL,
    ],
  });

  const credentialState = await AppleAuthentication.getCredentialStateAsync(
    credential.user,
  );

  if (
    credentialState ===
    AppleAuthentication.AppleAuthenticationCredentialState.AUTHORIZED
  ) {
    const { identityToken, fullName } = credential;
    console.log(
      "[Apple Sign In] Authentication succeeded. Token: ",
      identityToken,
    );
    const fullUserName =
      fullName && fullName?.givenName
        ? `${fullName.givenName} ${fullName?.familyName}`
        : null;
    return { token: identityToken, fullName: fullUserName };
  }
}
function AppleLoginButton() {
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  const { signIn } = useSession();

  const handlePress = async () => {
    setIsLoading(true);
    try {
      const res = await appleSignInRequest2();
      console.log("[Apple Sign In] Response: ", res);
      if (!res?.token) {
        setIsLoading(false);
        return;
      }

      const postData = {
        access_token: res.token,
        full_name: res?.fullName,
      };

      console.log("[Apple Sign In] postData: ", postData);

      const axiosConfig = {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      };

      const authToken = await axios.post(
        CONFIG.APPLE_SIGN_IN.WEB_CALLBACK_URL,
        postData,
        axiosConfig,
      );

      if (authToken?.data?.data) {
        await signIn(authToken?.data?.data); // signIn işlemini bekle
        router.replace("/");
      }
    } catch (error: AppleError | any) {
      // if (error.code === "ERR_REQUEST_CANCELED") {
      //   console.log("[Apple Sign In] İşlem iptal edildi.");
      // } else {
      //   console.error("Apple Sign In failed:", error);
      //   Alert.alert("Error", error?.response?.data?.message || "Server Error");
      // }
      if (error.code === "ERR_REQUEST_CANCELED") {
        console.log("[Apple Sign In] İşlem iptal edildi.");
      } else if (error.code === "ERR_REQUEST_FAILED") {
        console.error("Apple Sign In failed:", error);
      } else if (error.code === "ERR_REQUEST_NOT_HANDLED") {
        console.error("Apple Sign In failed:", error);
      } else if (error.code === "ERR_REQUEST_NOT_INTERACTIVE") {
        console.error("Apple Sign In failed:", error);
      } else {
        console.log("hata");
      }
    } finally {
      setIsLoading(false);
    }
  };

  if (!AppleAuthentication.isAvailableAsync()) {
    return null;
  }

  return (
    <IconButton
      onPress={handlePress}
      isLoading={isLoading}
      provider={CONFIG.SIGN_IN_METHOD.APPLE}
      variant="outline-apple"
    />
  );
}

AppleLoginButton.displayName = "AppleLoginButton";

export default AppleLoginButton;