import type { Transaction } from "../generated/kysely-tailordb";
import { ChannelNotFoundError, InvalidChannelStatusError } from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface DeactivateChannelInput {
  channelId: string;
}

export async function run(db: Transaction, input: DeactivateChannelInput, ctx: CommandContext) {
  void ctx;
  const channel = await db
    .selectFrom("Channel")
    .selectAll()
    .where("id", "=", input.channelId)
    .forUpdate()
    .executeTakeFirst();
  if (!channel) {
    return err(new ChannelNotFoundError(input.channelId));
  }
  if (channel.status !== "ACTIVE") {
    return err(new InvalidChannelStatusError(input.channelId));
  }
  const updated = await db
    .updateTable("Channel")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", input.channelId)
    .returningAll()
    .executeTakeFirst();
  return ok({ channel: updated! });
}
