import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { ChannelNotFoundError } from "../lib/errors.generated"; import type { ChannelId } from "./createNotificationChannel"; export interface ActivateNotificationChannelInput { channelId: ChannelId; } /** * Sets a registered NotificationChannel's enabled flag to true. Idempotent no-op when already enabled; errors when the channel is not registered. */ export async function run( db: Transaction, input: ActivateNotificationChannelInput, _ctx: CommandContext, ) { const { channelId } = input; const existing = await db .selectFrom("NotificationChannel") .selectAll() .where("channelId", "=", channelId) .forUpdate() .executeTakeFirst(); if (!existing) { return err(new ChannelNotFoundError(channelId)); } if (existing.enabled) { return ok({ channel: existing }); } const now = new Date(); const channel = await db .updateTable("NotificationChannel") .set({ enabled: true, updatedAt: now }) .where("channelId", "=", channelId) .returningAll() .executeTakeFirstOrThrow(); return ok({ channel }); }