"use server";

import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";

/** Register this browser's FCM token — attached to the account when signed in,
    stored as an anonymous website-visitor subscription otherwise. */
export async function registerPushTokenAction(token: string, userAgent?: string) {
  const user = await getCurrentUser();
  if (!token || token.length > 4096) return { ok: false };
  await db.pushToken.upsert({
    where: { token },
    create: { token, userId: user?.id ?? null, userAgent: userAgent?.slice(0, 200) },
    // token may move between accounts on a shared browser; a login upgrades an anonymous row
    update: { userId: user?.id ?? undefined },
  });
  return { ok: true };
}

/** Forget this browser's token (visitor or user turned notifications off). */
export async function removePushTokenAction(token: string) {
  if (!token) return { ok: false };
  // Knowing the device token is proof of owning the device — no login required.
  await db.pushToken.deleteMany({ where: { token } });
  return { ok: true };
}
