import React, { useEffect } from "react";
import { ClientProvider, useAuthHeader } from "./graphql/client";
import AppNavigator from "./navigation/app-navigator";

import { DEV_USER_ID } from "./config";
import AsyncStorage from "@react-native-async-storage/async-storage";

// TODO: move to different file?
const SetAuthHeaderBasedOnEnv = () => {
	const { setAuthHeader } = useAuthHeader();


	useEffect(() => {
		const setAuthAsync = async () => {
			if (DEV_USER_ID) {
				console.log("Setting fake authorization user to: ", DEV_USER_ID);
				setAuthHeader({ key: "user_id", value: DEV_USER_ID });
			} else {
				// Fetch token for authenticated users in production
				const token = await AsyncStorage.getItem('token'); // get from not firebase auth ASYNC
				if (token) {
					console.log("Setting firebase auth token");
					setAuthHeader({ key: "Authorization", value: `Bearer ${token}` });
				}
			}
		};

		setAuthAsync();
	}, [setAuthHeader]);

	return null;
};

const App: React.FC = () => {
	return (
		<ClientProvider>
			<SetAuthHeaderBasedOnEnv />
			<AppNavigator />
		</ClientProvider>
	);
};

export default function Root() {
	return (
		<React.StrictMode>
			<App />
		</React.StrictMode>
	);
}
