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

/**
 * Function: deactivatePartner
 *
 * Transitions a business partner from ACTIVE to INACTIVE status,
 * preserving it for audit trails while preventing new transactions.
 */
export async function run(db: Transaction, input: DeactivatePartnerInput) {
  const result = await executeTransition({
    db,
    tableName: "BusinessPartner",
    statusField: "status",
    id: input.id,
    transition: "deactivatePartner",
    lifecycle: businessPartnerLifecycle,
    errors: { notFound: PartnerNotFoundError, invalidTransition: InvalidStateTransitionError },
  });
  if (!result.ok) return result;
  return ok({ partner: result.value });
}
