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

export interface ActivateUnitInput {
  unitId: string;
}

/**
 * Function: activateUnit
 *
 * Re-enables a previously deactivated unit of measure, making it available
 * for new product assignments and quantity conversions.
 */
export async function run(db: Transaction, input: ActivateUnitInput) {
  // 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. If already active, return unit (idempotent)
  if (unit.isActive) {
    return ok({ unit });
  }

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

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