import { ok, err } from "@tailor-platform/erp-kit/core";
import { Transaction } from "../generated/kysely-tailordb";
import { DuplicateCodeError, MissingRequiredFieldError } from "../lib/errors.generated";

export interface CreateProductAttributeInput {
  code: string;
  name: string;
}

/**
 * Function: createProductAttribute
 *
 * Creates a new product attribute with a unique code.
 * All attributes are variant axes with predefined values.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreateProductAttributeInput & CF,
) {
  const { code, name, ...customFields } = input;

  if (!code?.trim()) {
    return err(new MissingRequiredFieldError("code"));
  }
  if (!name?.trim()) {
    return err(new MissingRequiredFieldError("name"));
  }

  // Check code uniqueness
  const existing = await db
    .selectFrom("ProductAttribute")
    .select("id")
    .where("code", "=", code)
    .forUpdate()
    .executeTakeFirst();
  if (existing) {
    return err(new DuplicateCodeError(code));
  }

  const attribute = await db
    .insertInto("ProductAttribute")
    .values({
      ...(customFields as Record<string, unknown>),
      code,
      name,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ productAttribute: attribute });
}
