import {
    getMessaging,
    requestPermission,
    getToken,
    onTokenRefresh,
    AuthorizationStatus,
} from '@react-native-firebase/messaging';
import notifee, { AndroidImportance } from '@notifee/react-native';
import { post } from '@/services/api';

export async function registerDeviceToken(authToken: string): Promise<void> {
    const messaging = getMessaging();
    const status = await requestPermission(messaging);
    const granted =
        status === AuthorizationStatus.AUTHORIZED ||
        status === AuthorizationStatus.PROVISIONAL;

    if (!granted) return;

    const fcmToken = await getToken(messaging);

    await fetch(`${process.env.EXPO_PUBLIC_API_URL}/api/device-tokens/register`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`,
        },
        body: JSON.stringify({ token: fcmToken }),
    });
}

export function listenForTokenRefresh(authToken: string): () => void {
    return onTokenRefresh(getMessaging(), async (newToken) => {
        await post('/device-tokens/register', { token: newToken }, authToken);
    });
}

export async function displayLocalNotification(title?: string, body?: string) {
    if (!title && !body) return;

    const channelId = await notifee.createChannel({
        id: 'default',
        name: 'General',
        importance: AndroidImportance.HIGH,
    });

    await notifee.displayNotification({
        title,
        body,
        android: {
            channelId,
            pressAction: { id: 'default' },
        },
    });
}