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

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 (input.type !== undefined && !input.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 updates: Updateable<"Channel"> = {};
  if (input.type !== undefined) updates.type = input.type;
  if (input.name !== undefined) updates.name = input.name;
  if (input.code !== undefined) updates.code = input.code;
  if (input.settings !== undefined) {
    updates.settings = input.settings ? encodeJson(input.settings) : null;
  }

  if (Object.keys(updates).length === 0) {
    return ok({ channel });
  }

  const updated = await db
    .updateTable("Channel")
    .set(updates)
    .where("id", "=", input.channelId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ channel: updated });
}
