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

export interface DeleteProductAttributeInput {
  id: string;
}

/**
 * Function: deleteProductAttribute
 *
 * Deletes an attribute that is not assigned to any product.
 */
export async function run(db: Transaction, input: DeleteProductAttributeInput) {
  const { id } = input;

  const attribute = await db
    .selectFrom("ProductAttribute")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

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

  // Check if assigned to any product
  const assignments = await db
    .selectFrom("ProductAttributeAssignment")
    .select("id")
    .where("attributeId", "=", id)
    .executeTakeFirst();
  if (assignments) {
    return err(new AttributeInUseError(id));
  }

  // Remove attribute values
  await db.deleteFrom("ProductAttributeValue").where("attributeId", "=", id).execute();

  // Delete attribute
  await db.deleteFrom("ProductAttribute").where("id", "=", id).execute();

  return ok({ id });
}
