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<CF extends Record<string, unknown>>(
  db: Transaction,
  input: UpdateChannelInput & Partial<CF>,
  ctx: CommandContext,
) {
  void ctx;
  const { channelId, type, name, code, settings, ...customFields } = input;
  const channel = await db
    .selectFrom("Channel")
    .selectAll()
    .where("id", "=", channelId)
    .forUpdate()
    .executeTakeFirst();
  if (!channel) {
    return err(new ChannelNotFoundError(channelId));
  }
  if (type !== undefined && !type) {
    return err(new InvalidChannelTypeError(channelId));
  }

  if (name && 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 === name)) {
      return err(new DuplicateChannelNameError(name));
    }
  }

  const updates: Updateable<"Channel"> = { ...(customFields as Updateable<"Channel">) };
  if (type !== undefined) updates.type = type;
  if (name !== undefined) updates.name = name;
  if (code !== undefined) updates.code = code;
  if (settings !== undefined) {
    updates.settings = settings ? encodeJson(settings) : null;
  }

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

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

  return ok({ channel: updated });
}
