import { PushNotifications } from '@capacitor/push-notifications';
import { Capacitor } from '@capacitor/core';
import { Device } from '@capacitor/device';

export async function setupPushNotifications(): Promise<void> {
    if (!Capacitor.isNativePlatform()) return;

    const perm = await PushNotifications.requestPermissions();
    if (perm.receive !== 'granted') return;

    await PushNotifications.register();

    // Cihaz token'ını sunucuya gönder
    PushNotifications.addListener('registration', async (token) => {
        const csrfToken = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
        await fetch('/api/mobile/register-push-token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
            },
            body: JSON.stringify({
                token: token.value,
                platform: Capacitor.getPlatform(), // 'ios' veya 'android'
                device_info: await Device.getInfo(),
            }),
        });
    });

    // Kayıt hatası
    PushNotifications.addListener('registrationError', (error) => {
        console.error('[ONOX Push] Kayıt hatası:', error);
        window.dispatchEvent(new CustomEvent('push:error', { detail: error }));
    });

    // Ön planda bildirim geldi — uygulama içi banner göster
    PushNotifications.addListener('pushNotificationReceived', (notification) => {
        window.dispatchEvent(new CustomEvent('push:received', { detail: notification }));
    });

    // Kullanıcı bildirimine dokundu — derin bağlantıyı takip et
    PushNotifications.addListener('pushNotificationActionPerformed', (action) => {
        const data = action.notification.data as Record<string, string>;
        if (data.path) {
            window.location.assign(data.path);
        }
    });
}

export async function unregisterPushToken(token: string): Promise<void> {
    if (!Capacitor.isNativePlatform()) return;
    const csrfToken = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
    await fetch('/api/mobile/unregister-push-token', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': csrfToken,
        },
        body: JSON.stringify({ token }),
    });
}
