import { getCurrentUser } from '@/firebase/firebase.utils';
import { UPDATE_FCM_TOKEN } from '@/graphql/bodyshop.queries';
import { client } from '@/graphql/client';
import Constants from 'expo-constants';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';

Notifications.setNotificationHandler({
    handleNotification: async () => ({
        shouldPlaySound: false,
        shouldSetBadge: false,
        shouldShowBanner: true,
        shouldShowList: true,
    }),
});


async function registerForPushNotificationsAsync() {
    console.log("Registering for push notifications...");
    if (Platform.OS === 'android') {
        await Notifications.setNotificationChannelAsync('default', {
            name: 'default',
            importance: Notifications.AndroidImportance.MAX,
            vibrationPattern: [0, 250, 250, 250],
            lightColor: '#FF231F7C',
        });
    }

    if (Device.isDevice) {
        const { status: existingStatus } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus;
        if (existingStatus !== 'granted') {
            const { status } = await Notifications.requestPermissionsAsync();
            finalStatus = status;
        }
        if (finalStatus !== 'granted') {
            throw new Error('Permission not granted to get push token for push notification!');
        }
        const projectId =
            Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;
        if (!projectId) {
            throw new Error('Project ID not found');
        }
        try {
            const pushTokenString = (
                await Notifications.getExpoPushTokenAsync({
                    projectId,
                })
            ).data;
            console.log(pushTokenString);

            //Write the FCM token to database. 

            await client.mutate({
                mutation: UPDATE_FCM_TOKEN,
                variables: {
                    email: (await getCurrentUser()).email,
                    token: { [pushTokenString]: { pushTokenString, platform: Platform.OS, timestamp: Date.now() } },
                },
            });
            return pushTokenString;
        } catch (error) {
            throw error
        }
    } else {
        throw new Error('Must use physical device for push notifications');
    }
}

export { registerForPushNotificationsAsync };
