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

export interface CreateSalesPriceListInput {
  companyId: string;
  customerId?: string | null;
  channelId?: string | null;
  name: string;
  code?: string;
  priority?: number;
  notes?: string;
}

export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreateSalesPriceListInput & 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.name) {
    return err(new IdentifierRequiredError("sales-price-list.name"));
  }
  const { companyId, customerId, channelId, name, code, priority, notes, ...customFields } = input;
  const salesPriceList = await db
    .insertInto("SalesPriceList")
    .values({
      ...(customFields as Record<string, unknown>),
      companyId,
      customerId: customerId ?? null,
      channelId: channelId ?? null,
      name,
      code: code ?? null,
      priority: priority ?? 0,
      status: "DRAFT",
      notes: notes ?? null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesPriceList });
}
