'use server' import type { UpdateWebhookInput, WebhookResult } from './types' import { requireRole, UserRole } from '@admin/auth/middleware' import db from '@admin/db' import { webhookSubscriptions, webhooks } from '@admin/db/schema' import { toActionError } from '@admin/utils/error/to-action-error' import { and, eq, notInArray } from 'drizzle-orm' import { updateTag } from 'next/cache' import { webhooksCacheTags } from './types' export async function updateWebhook(id: string, input: UpdateWebhookInput): Promise { await requireRole([UserRole.ADMIN]) try { const updated = await db.transaction(async (tx) => { const [row] = await tx .update(webhooks) .set({ ...(input.name !== undefined ? { name: input.name } : {}), ...(input.url !== undefined ? { url: input.url } : {}), ...(input.enabled !== undefined ? { enabled: input.enabled } : {}), updatedAt: new Date().toISOString() }) .where(eq(webhooks.id, id)) .returning() if (!row) throw new Error('Webhook not found') if (input.events !== undefined) { const events = input.events if (events.length > 0) { await tx .delete(webhookSubscriptions) .where( and( eq(webhookSubscriptions.webhookId, id), notInArray(webhookSubscriptions.event, events) ) ) await tx .insert(webhookSubscriptions) .values(events.map((event) => ({ webhookId: id, event }))) .onConflictDoNothing() } else { await tx.delete(webhookSubscriptions).where(eq(webhookSubscriptions.webhookId, id)) } } return row }) updateTag(webhooksCacheTags.endpoints) updateTag(webhooksCacheTags.subscriptions) return { success: true, webhook: { id: updated.id, name: updated.name, url: updated.url, enabled: updated.enabled, createdAt: updated.createdAt, updatedAt: updated.updatedAt } } } catch (error) { console.error('Error updating webhook:', error) return { success: false, error: toActionError(error, 'Failed to update webhook') } } }