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

export interface CreateChannelInput {
  companyId: string;
  type: string;
  name: string;
  code?: string;
  settings?: Record<string, unknown> | null;
}

export async function run(db: Transaction, input: CreateChannelInput, ctx: CommandContext) {
  void ctx;
  const company = await db
    .selectFrom("Company")
    .selectAll()
    .where("id", "=", input.companyId)
    .executeTakeFirst();
  if (!company) {
    return err(new CompanyNotFoundError(input.companyId));
  }
  if (!input.type) {
    return err(new InvalidChannelTypeError(input.companyId));
  }

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

  const channel = await db
    .insertInto("Channel")
    .values({
      companyId: input.companyId,
      type: input.type,
      name: input.name,
      code: input.code ?? null,
      status: "DRAFT",
      settings: input.settings ? encodeJson(input.settings) : null,
      lastSyncAt: null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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