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

export type UpdateChannelInput = {
  channelId: string;
  type?: string;
  name?: string;
  code?: string | null;
  settings?: Record<string, unknown> | null;
};
export async function run(db: Transaction, input: UpdateChannelInput, 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 (!["DRAFT", "ACTIVE", "INACTIVE"].includes(channel.status)) {
    return err(new ChannelNotEditableError(input.channelId));
  }
  const type = input.type ?? channel.type;
  if (!type) {
    return err(new InvalidChannelTypeError(input.channelId));
  }

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

  const updated = await db
    .updateTable("Channel")
    .set({
      type,
      name: input.name ?? channel.name,
      code: input.code === undefined ? channel.code : input.code,
      settings:
        input.settings === undefined
          ? channel.settings
          : input.settings
            ? encodeJson(input.settings)
            : null,
      updatedAt: new Date(),
    })
    .where("id", "=", input.channelId)
    .returningAll()
    .executeTakeFirst();

  return ok({ channel: updated! });
}
