import { executeTransition, ok } from "@tailor-platform/erp-kit/core";
import { itemLifecycle } from "../db/item.lifecycle.generated";
import { Transaction } from "../generated/kysely-tailordb";
import { InvalidStateTransitionError, ItemNotFoundError } from "../lib/errors.generated";

export interface DeactivateItemInput {
  id: string;
}

/**
 * Function: deactivateItem
 *
 * Transitions an item from ACTIVE to INACTIVE status,
 * preserving it for audit trails while preventing new transactions.
 */
export async function run(db: Transaction, input: DeactivateItemInput) {
  const result = await executeTransition({
    db,
    tableName: "Item",
    statusField: "status",
    id: input.id,
    transition: "deactivate",
    lifecycle: itemLifecycle,
    errors: { notFound: ItemNotFoundError, invalidTransition: InvalidStateTransitionError },
  });
  if (!result.ok) return result;
  return ok({ item: result.value });
}
