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

export interface DeleteProductInput {
  id: string;
}

/**
 * Function: deleteProduct
 *
 * Permanently deletes a DRAFT product and all associated assignments.
 */
export async function run(db: Transaction, input: DeleteProductInput) {
  const { id } = input;

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

  if (!product) {
    return err(new ProductNotFoundError(id));
  }

  if (product.status !== "DRAFT") {
    return err(new DeleteNotAllowedError(id));
  }

  // Remove attribute assignments
  await db.deleteFrom("ProductAttributeAssignment").where("productId", "=", id).execute();

  // Remove category assignments
  await db.deleteFrom("ProductCategoryAssignment").where("productId", "=", id).execute();

  // Delete product
  await db.deleteFrom("Product").where("id", "=", id).execute();

  return ok({ id });
}
