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

export interface RemoveProductFromCategoryInput {
  productId: string;
  categoryId: string;
}

/**
 * Function: removeProductFromCategory
 *
 * Removes a product-category assignment.
 */
export async function run(db: Transaction, input: RemoveProductFromCategoryInput) {
  const { productId, categoryId } = input;

  const assignment = await db
    .selectFrom("ProductCategoryAssignment")
    .selectAll()
    .where("productId", "=", productId)
    .where("categoryId", "=", categoryId)
    .forUpdate()
    .executeTakeFirst();
  if (!assignment) {
    return err(new AssignmentNotFoundError(`${productId}:${categoryId}`));
  }

  await db.deleteFrom("ProductCategoryAssignment").where("id", "=", assignment.id).execute();

  return ok({ id: assignment.id });
}
