import { ok } from "@tailor-platform/erp-kit/core";
import { executeTransition } from "../../../shared/defineLifecycle";
import { productLifecycle } from "../db/product.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { ProductNotFoundError, InvalidStateTransitionError } from "../lib/errors.generated";

export interface ActivateProductInput {
  id: string;
}

/**
 * Function: activateProduct
 *
 * Transitions a product from DRAFT to ACTIVE.
 */
export async function run(db: Transaction, input: ActivateProductInput) {
  const result = await executeTransition({
    db,
    tableName: "Product",
    statusField: "status",
    id: input.id,
    transition: "activate",
    lifecycle: productLifecycle,
    errors: { notFound: ProductNotFoundError, invalidTransition: InvalidStateTransitionError },
  });
  if (!result.ok) return result;
  return ok({ product: result.value });
}
