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

export interface DeleteProductCategoryInput {
  id: string;
}

/**
 * Function: deleteProductCategory
 *
 * Deletes a leaf category with no product assignments.
 */
export async function run(db: Transaction, input: DeleteProductCategoryInput) {
  const { id } = input;

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

  if (!category) {
    return err(new CategoryNotFoundError(id));
  }

  const child = await db
    .selectFrom("ProductCategory")
    .select("id")
    .where("parentId", "=", id)
    .executeTakeFirst();
  if (child) {
    return err(new HasChildrenError(id));
  }

  const assignment = await db
    .selectFrom("ProductCategoryAssignment")
    .select("id")
    .where("categoryId", "=", id)
    .executeTakeFirst();
  if (assignment) {
    return err(new HasAssignmentsError(id));
  }

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

  return ok({ id });
}
