'use server' import { revalidateTag } from 'next/cache' import { z } from 'zod' import { PERMS } from '@/lib/permission-slugs' import { prisma } from '@/lib/prisma' import { adminAction } from '@/lib/safe-action' import { actionOk } from '@/lib/safe-action-shared' const toggleWatchSchema = z.object({ targetUserId: z.coerce.number().int().positive(), reason: z.string().max(255).optional(), }) /** * Toggle a watch entry for the calling staff on the given target user. * If a row already exists it's removed; otherwise it's created with the * provided reason (defaulting to empty). Returns the resulting state so * the UI can flip the badge without re-fetching. */ export const toggleUserWatch = adminAction( { permission: PERMS.USERS_VIEW, schema: toggleWatchSchema }, async (ctx) => { const staffId = ctx.session.user.id const { targetUserId, reason } = ctx.data const existing = await prisma.userWatch.findUnique({ where: { staffId_targetUserId: { staffId, targetUserId } }, }) if (existing) { await prisma.userWatch.delete({ where: { id: existing.id } }) revalidateTag(`user-watch:${staffId}`, { expire: 0 }) return actionOk({ watching: false }) } await prisma.userWatch.create({ data: { staffId, targetUserId, reason: reason ?? '' }, }) revalidateTag(`user-watch:${staffId}`, { expire: 0 }) return actionOk({ watching: true }) }, )