import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction, Updateable } from "../generated/kysely-tailordb";
import { InvalidListPriorityError, PriceListNotFoundError } from "../lib/errors.generated";

export type UpdatePurchasePriceListInput = {
  id: string;
  name?: string;
  code?: string | null;
  priority?: number;
  notes?: string | null;
};
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: UpdatePurchasePriceListInput & Partial<CF>,
  _ctx: CommandContext,
) {
  const { id, name, code, priority, notes, ...customFields } = input;
  const existing = await db
    .selectFrom("PurchasePriceList")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();
  if (!existing) {
    return err(new PriceListNotFoundError(id));
  }

  if (priority !== undefined && priority < 0) {
    return err(new InvalidListPriorityError(String(priority)));
  }

  const updates: Updateable<"PurchasePriceList"> = {
    ...(customFields as Updateable<"PurchasePriceList">),
  };
  if (name !== undefined) updates.name = name;
  if (code !== undefined) updates.code = code;
  if (priority !== undefined) updates.priority = priority;
  if (notes !== undefined) updates.notes = notes;

  if (Object.keys(updates).length === 0) {
    return ok({ purchasePriceList: existing });
  }

  const purchasePriceList = await db
    .updateTable("PurchasePriceList")
    .set(updates)
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePriceList });
}
