import webpush from 'web-push';

if (!process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
    console.warn("VAPID keys are missing. Push notifications will not work.");
} else {
    webpush.setVapidDetails(
        process.env.VAPID_SUBJECT || 'mailto:admin@localhost',
        process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY,
        process.env.VAPID_PRIVATE_KEY
    );
}

interface PushSubscriptionData {
    endpoint: string;
    p256dh: string;
    auth: string;
}

export async function sendPushNotification(subscription: PushSubscriptionData, payload: any) {
    try {
        console.log(`[PushLib] Sending to ${subscription.endpoint.slice(0, 30)}...`);
        const result = await webpush.sendNotification({
            endpoint: subscription.endpoint,
            keys: {
                p256dh: subscription.p256dh,
                auth: subscription.auth,
            }
        }, JSON.stringify(payload));
        console.log(`[PushLib] Success: ${result.statusCode}`);
        return { success: true, statusCode: 201 };
    } catch (error: any) {
        if (error.statusCode === 410 || error.statusCode === 404) {
            // Subscription is gone
            return { success: false, statusCode: error.statusCode };
        }
        console.error("Error sending push:", error);
        return { success: false, statusCode: error.statusCode || 500 };
    }
}
