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

export interface ActivateChannelInput {
  channelId: string;
}

export async function run(db: Transaction, input: ActivateChannelInput, 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 !== "DRAFT") {
    return err(new InvalidChannelStatusError(input.channelId));
  }
  if (!channel.type) {
    return err(new InvalidChannelTypeError(input.channelId));
  }

  const siblings = await db
    .selectFrom("Channel")
    .selectAll()
    .where("companyId", "=", channel.companyId)
    .execute();
  if (siblings.some((item) => item.id !== channel.id && item.name === channel.name)) {
    return err(new DuplicateChannelNameError(channel.name));
  }

  const updated = await db
    .updateTable("Channel")
    .set({ status: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.channelId)
    .returningAll()
    .executeTakeFirst();
  return ok({ channel: updated! });
}
