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

export interface ActivateCategoryInput {
  categoryId: string;
}

/**
 * Function: activateCategory
 *
 * Re-enables a previously deactivated UoM category, making it and its units
 * available for new product assignments and transactions.
 */
export async function run(db: Transaction, input: ActivateCategoryInput) {
  // 1. Find category by ID
  const uoMCategory = await db
    .selectFrom("UoMCategory")
    .selectAll()
    .where("id", "=", input.categoryId)
    .forUpdate()
    .executeTakeFirst();

  // 2. If not found, throw error
  if (!uoMCategory) {
    return err(new UomCategoryNotFoundError(input.categoryId));
  }

  // 3. If already active, return category (idempotent)
  if (uoMCategory.isActive) {
    return ok({ uoMCategory });
  }

  // 4. Update isActive = true
  const updatedCategory = await db
    .updateTable("UoMCategory")
    .set({
      isActive: true,
      updatedAt: new Date(),
    })
    .where("id", "=", input.categoryId)
    .returningAll()
    .executeTakeFirst();

  // 5. Return updated category
  return ok({ uoMCategory: updatedCategory! });
}
