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

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