import { ok, err } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { ValueNotFoundError, InvalidLabelError, DuplicateValueError, } from "../lib/errors.generated"; export type UpdateProductAttributeValueInput = { id: string; label: string; }; /** * Function: updateProductAttributeValue * * Updates the display label of an existing attribute value. */ export async function run(db: Transaction, input: UpdateProductAttributeValueInput) { const { id, label } = input; const value = await db .selectFrom("ProductAttributeValue") .selectAll() .where("id", "=", id) .forUpdate() .executeTakeFirst(); if (!value) { return err(new ValueNotFoundError(id)); } if (!label?.trim()) { return err(new InvalidLabelError(id)); } // Check label uniqueness within same attribute const existingValue = await db .selectFrom("ProductAttributeValue") .selectAll() .where("attributeId", "=", value.attributeId) .where("label", "=", label) .where("id", "!=", id) .executeTakeFirst(); if (existingValue) { return err(new DuplicateValueError(label)); } const updated = await db .updateTable("ProductAttributeValue") .set({ label }) .where("id", "=", id) .returningAll() .executeTakeFirstOrThrow(); return ok({ value: updated }); }