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

export interface DeactivateChartOfAccountsInput {
  id: string;
}

/**
 * Function: deactivateChartOfAccounts
 *
 * Transitions a Chart of Accounts from ACTIVE to ARCHIVED status.
 * This is a one-way transition; reactivation from ARCHIVED is not permitted.
 */
export async function run(
  db: Transaction,
  input: DeactivateChartOfAccountsInput,
  _ctx: CommandContext,
) {
  const result = await executeTransition({
    db,
    tableName: "ChartOfAccounts",
    statusField: "status",
    id: input.id,
    transition: "deactivate",
    lifecycle: chartOfAccountsLifecycle,
    errors: {
      notFound: ChartOfAccountsNotFoundError,
      invalidTransition: InvalidStateTransitionError,
    },
  });
  if (!result.ok) return result;
  return ok({ chartOfAccounts: result.value });
}
