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 ActivateItemInput {
  id: string;
}

/**
 * Function: activateItem
 *
 * Transitions an item from DRAFT to ACTIVE status.
 */
export async function run(db: Transaction, input: ActivateItemInput) {
  const result = await executeTransition({
    db,
    tableName: "Item",
    statusField: "status",
    id: input.id,
    transition: "activate",
    lifecycle: itemLifecycle,
    errors: { notFound: ItemNotFoundError, invalidTransition: InvalidStateTransitionError },
  });
  if (!result.ok) return result;
  return ok({ item: result.value });
}
