"use server";

import prisma from "@/lib/prisma";

export async function subscribeUser(planId: string, subscription: any) {
    if (!subscription || !subscription.endpoint || !subscription.keys) {
        throw new Error("Invalid subscription object");
    }

    const { endpoint, keys: { p256dh, auth } } = subscription;

    // Use upsert to handle updates gracefully
    // If endpoint exists, update the planId. A device follows the last plan logged into (or explicitly subscribed to).

    // Check existence first to decide logic (or just upsert)
    // Actually, if we want to allow multiple plans per device, we need a different model.
    // For now, simple model: One device -> One Plan.

    await prisma.pushSubscription.upsert({
        where: { endpoint },
        create: {
            planId,
            endpoint,
            p256dh,
            auth,
        },
        update: {
            planId,
            p256dh,
            auth,
        }
    });

    return { success: true };
}

export async function unsubscribeUser(endpoint: string) {
    if (!endpoint) return;

    await prisma.pushSubscription.deleteMany({
        where: { endpoint },
    });

    return { success: true };
}

export async function getVapidPublicKey() {
    return process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
}
