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

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

export async function run(db: Transaction, input: CreateSalesPriceListInput, 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.name) {
    return err(new IdentifierRequiredError("sales-price-list.name"));
  }
  const salesPriceList = await db
    .insertInto("SalesPriceList")
    .values({
      companyId: input.companyId,
      customerId: input.customerId ?? null,
      channelId: input.channelId ?? null,
      name: input.name,
      code: input.code ?? null,
      priority: input.priority ?? 0,
      status: "DRAFT",
      notes: input.notes ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPriceList: salesPriceList! });
}
