import { ok, executeTransition } from "@tailor-platform/erp-kit/core";
import { businessPartnerLifecycle } from "../db/businessPartner.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidStateTransitionError, PartnerNotFoundError } from "../lib/errors.generated";

export interface ReactivatePartnerInput {
  id: string;
}

/**
 * Function: reactivatePartner
 *
 * Transitions a business partner from INACTIVE back to ACTIVE status,
 * restoring a previously deactivated partner for transactions.
 */
export async function run(db: Transaction, input: ReactivatePartnerInput) {
  const result = await executeTransition({
    db,
    tableName: "BusinessPartner",
    statusField: "status",
    id: input.id,
    transition: "reactivatePartner",
    lifecycle: businessPartnerLifecycle,
    errors: { notFound: PartnerNotFoundError, invalidTransition: InvalidStateTransitionError },
  });
  if (!result.ok) return result;
  return ok({ partner: result.value });
}
