import AsyncStorage from "@react-native-async-storage/async-storage";
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth";
import { Alert } from "react-native";

export const handleSignInWithPhoneNumber = async (
	phoneNumber: string,
): Promise<FirebaseAuthTypes.ConfirmationResult | undefined> => {
	if (!phoneNumber) {
		Alert.alert("Please enter a valid phone number with a country code");
		return;
	}
	try {
		const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
		return confirmation;
	} catch (err) {
		console.warn(err);
		Alert.alert(
			"There was an error. Make sure you are using a country code (ex: +1 for US)",
		);
	}
};

export const confirmCode = async (
	confirm: FirebaseAuthTypes.ConfirmationResult,
	code: string,
): Promise<void> => {
	try {
		await confirm.confirm(code);
	} catch {
		Alert.alert("Invalid code, please try again.");
	}
};

export const onAuthStateChanged = (
	// TODO: eslint not detecting ts?
	// eslint-disable-next-line no-unused-vars
	callback: (user: FirebaseAuthTypes.User | null) => void,
) => {
	return auth().onAuthStateChanged(callback);
};

export const getCurrentUserToken = async (): Promise<string | null> => {
	const user = auth().currentUser;
	if (user) {
		return await user.getIdToken();
	}
	return null;
};

export const handleSignOut = async (): Promise<void> => {
	await AsyncStorage.removeItem("token");
	await auth().signOut();
};
