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

export interface CreateProductAttributeValueInput {
  attributeId: string;
  label: string;
}

/**
 * Function: createProductAttributeValue
 *
 * Creates a new predefined value for an attribute.
 */
export async function run(db: Transaction, input: CreateProductAttributeValueInput) {
  const { attributeId, label } = input;

  // Check attribute exists
  const attribute = await db
    .selectFrom("ProductAttribute")
    .selectAll()
    .where("id", "=", attributeId)
    .executeTakeFirst();

  if (!attribute) {
    return err(new AttributeNotFoundError(attributeId));
  }

  // Validate label
  if (!label?.trim()) {
    return err(new InvalidLabelError(attributeId));
  }

  // Check label uniqueness within attribute
  const existingValue = await db
    .selectFrom("ProductAttributeValue")
    .selectAll()
    .where("attributeId", "=", attributeId)
    .where("label", "=", label)
    .forUpdate()
    .executeTakeFirst();

  if (existingValue) {
    return err(new DuplicateValueError(label));
  }

  const value = await db
    .insertInto("ProductAttributeValue")
    .values({
      attributeId,
      label,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ productAttributeValue: value });
}
