import type { Transaction } from "../generated/kysely-tailordb";
import { ChartOfAccountsNotFoundError, InvalidStateTransitionError } from "../lib/errors.generated";
import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface DeactivateChartOfAccountsInput {
  id: string;
  from?: 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 { id, from = ["ACTIVE"] } = input;

  // 1. Find CoA with forUpdate
  const existing = await db
    .selectFrom("ChartOfAccounts")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new ChartOfAccountsNotFoundError(id));
  }

  // 2. Must be in an allowed source status
  if (!from.includes(existing.status)) {
    return err(new InvalidStateTransitionError(id));
  }

  // 3. Update status to ARCHIVED
  const chartOfAccounts = await db
    .updateTable("ChartOfAccounts")
    .set({
      status: "ARCHIVED",
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ chartOfAccounts: chartOfAccounts! });
}
