/** @format */

import { GoogleSignin } from "@react-native-google-signin/google-signin";
import type { SocialAuthResult, SocialAuthService } from "./types";

const GOOGLE_WEB_CLIENT_ID = process.env.EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID?.trim() ?? "";
const GOOGLE_IOS_CLIENT_ID = process.env.EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID?.trim() ?? "";

function hasAndroidOAuthConfig() {
  return Boolean(GOOGLE_WEB_CLIENT_ID) && Boolean(GOOGLE_IOS_CLIENT_ID);
}

export const isGoogleAuthConfigured = Boolean(GOOGLE_WEB_CLIENT_ID) && hasAndroidOAuthConfig();

let isGoogleSigninConfigured = false;

function ensureGoogleSigninConfigured() {
  if (!isGoogleAuthConfigured || isGoogleSigninConfigured) {
    return;
  }

  GoogleSignin.configure({
    scopes: ["https://www.googleapis.com/auth/drive.readonly"],
    offlineAccess: false,
    hostedDomain: "",
    forceCodeForRefreshToken: false,
    webClientId: GOOGLE_WEB_CLIENT_ID,
    iosClientId: GOOGLE_IOS_CLIENT_ID,
    profileImageSize: 120,
  });
  isGoogleSigninConfigured = true;
}

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

    ensureGoogleSigninConfigured();
    await GoogleSignin.hasPlayServices();

    try {
      const response = await GoogleSignin.signIn();

      if (!response) {
        return { type: "cancelled" };
      }
      const tokens = await GoogleSignin.getTokens();

      if (!tokens.idToken) {
        throw new Error("Google sign-in did not return an ID token.");
      }

      return {
        type: "success",
        provider: "google",
        accessToken: tokens.idToken,
      };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);

      if (message.includes("DEVELOPER_ERROR")) {
        throw new Error("Google Sign-In is not configured correctly for this Android build.");
      }

      throw error;
    }
  },
};
