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

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

export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreateChannelInput & CF,
  ctx: CommandContext,
  organizationQueries: Pick<OrganizationQueries, "getCompany">,
) {
  const { company } = (await organizationQueries.getCompany(db, { id: input.companyId }, ctx))
    .value;
  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 { companyId, type, name, code, settings, ...customFields } = input;
  const channel = await db
    .insertInto("Channel")
    .values({
      ...(customFields as Record<string, unknown>),
      companyId,
      type,
      name,
      code: code ?? null,
      status: "DRAFT",
      settings: settings ? encodeJson(settings) : null,
      lastSyncAt: null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ channel });
}
