import { ok, executeTransition } from "@tailor-platform/erp-kit/core";
import { companyLifecycle } from "../db/company.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { CompanyNotFoundError, InvalidStateError } from "../lib/errors.generated";

export interface DeactivateCompanyInput {
  companyId: string;
}

/**
 * Function: deactivateCompany
 *
 * Transitions a company from ACTIVE to INACTIVE status, preventing it from
 * being used in new transactions while preserving historical data.
 */
export async function run(db: Transaction, input: DeactivateCompanyInput) {
  const result = await executeTransition({
    db,
    tableName: "Company",
    statusField: "status",
    id: input.companyId,
    transition: "deactivate",
    lifecycle: companyLifecycle,
    errors: { notFound: CompanyNotFoundError, invalidTransition: InvalidStateError },
  });
  if (!result.ok) return result;
  return ok({ company: result.value });
}
