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

export interface DeactivateUnitInput {
  unitId: string;
}

/**
 * Function: deactivateUnit
 *
 * Disables a unit of measure from being used in new product assignments
 * and quantity conversions while preserving all historical data.
 * Reference units cannot be deactivated.
 */
export async function run(db: Transaction, input: DeactivateUnitInput) {
  // 1. Find unit by ID
  const unit = await db
    .selectFrom("Unit")
    .selectAll()
    .where("id", "=", input.unitId)
    .forUpdate()
    .executeTakeFirst();

  // 2. If not found, throw error
  if (!unit) {
    return err(new UnitNotFoundError(input.unitId));
  }

  // 3. Check if unit is reference unit for its category
  const uoMCategory = await db
    .selectFrom("UoMCategory")
    .selectAll()
    .where("id", "=", unit.categoryId)
    .executeTakeFirst();

  if (uoMCategory?.referenceUnitId === unit.id) {
    return err(new CannotDeactivateReferenceUnitError(input.unitId));
  }

  // 4. If already inactive, return unit (idempotent)
  if (!unit.isActive) {
    return ok({ unit });
  }

  // 5. Update isActive = false
  const updatedUnit = await db
    .updateTable("Unit")
    .set({
      isActive: false,
      updatedAt: new Date(),
    })
    .where("id", "=", input.unitId)
    .returningAll()
    .executeTakeFirst();

  // 6. Return updated unit
  return ok({ unit: updatedUnit! });
}
