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 DeactivateNotificationChannelInput {
  channelId: ChannelId;
}

/**
 * Sets a registered NotificationChannel's enabled flag to false. Idempotent no-op when already disabled; errors when the channel is not registered.
 */
export async function run(
  db: Transaction,
  input: DeactivateNotificationChannelInput,
  _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: false, updatedAt: now })
    .where("channelId", "=", channelId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ channel });
}
