/** @format */

import { NativeModules, Platform } from "react-native";
import type { SocialAuthResult, SocialAuthService } from "./types";

const FACEBOOK_APP_ID = process.env.EXPO_PUBLIC_FACEBOOK_APP_ID?.trim() ?? "";
const hasFacebookNativeModule = Boolean(
  NativeModules.FBLoginManager && NativeModules.FBAccessToken,
);

export const isFacebookAuthConfigured =
  Boolean(FACEBOOK_APP_ID) && hasFacebookNativeModule;

function getFBSDK() {
  return require("react-native-fbsdk-next") as typeof import("react-native-fbsdk-next");
}

export const facebookAuthService: SocialAuthService = {
  async signIn(): Promise<SocialAuthResult> {
    if (!isFacebookAuthConfigured) {
      return { type: "cancelled" };
    }

    const { LoginManager, AccessToken, AuthenticationToken } = getFBSDK();

    const result =
      Platform.OS === "ios"
        ? await LoginManager.logInWithPermissions(
            ["public_profile", "email"],
            "limited",
          )
        : await LoginManager.logInWithPermissions([
            "public_profile",
            "email",
          ]);

    if (result.isCancelled) {
      return { type: "cancelled" };
    }

    let accessToken = null;

    if (Platform.OS === "ios") {
      const tokens = await AuthenticationToken.getAuthenticationTokenIOS();
      accessToken = tokens?.authenticationToken.toString();
    } else {
      const tokens = await AccessToken.getCurrentAccessToken();
      accessToken = tokens?.accessToken.toString();
    }

    if (!accessToken) {
      throw new Error("Facebook sign-in did not return an access token.");
    }

    return {
      type: "success",
      provider: "facebook",
      accessToken,
    };
  },
};
