import webPush from "web-push";

export default defineEventHandler(() => {
    // Generate once and set in .env for production
    if (process.env.NODE_ENV === "production") {
        if (
            !process.env.VAPID_PRIVATE_KEY ||
            !process.env.NUXT_PUBLIC_VAPID_KEY
        ) {
            throw createError({
                statusCode: 500,
                statusMessage: "VAPID keys not configured in production",
            });
        }
        return { publicKey: process.env.NUXT_PUBLIC_VAPID_KEY };
    }

    // Development: Generate and reuse
    if (!process.env.VAPID_PRIVATE_KEY) {
        const vapidKeys = webPush.generateVAPIDKeys();
        process.env.VAPID_PRIVATE_KEY = vapidKeys.privateKey;
        process.env.NUXT_PUBLIC_VAPID_KEY = vapidKeys.publicKey;
    }

    return { publicKey: process.env.NUXT_PUBLIC_VAPID_KEY };
});
