import { Transaction } from "../generated/kysely-tailordb";
import {
  ValueNotFoundError,
  InvalidLabelError,
  DuplicateValueError,
} from "../lib/errors.generated";
import { ok, err } from "@tailor-platform/erp-kit/module";

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, updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ value: updated! });
}
