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

export interface ReactivateAccountInput {
  id: string;
  from?: string[];
}

/**
 * Function: reactivateAccount
 *
 * Transitions a GL account from INACTIVE back to ACTIVE status, making it
 * eligible to receive journal postings again. Clears any previously mapped
 * successor account.
 */
export async function run(db: Transaction, input: ReactivateAccountInput, _ctx: CommandContext) {
  const { id, from = ["INACTIVE"] } = input;

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

  if (!account) {
    return err(new AccountNotFoundError(id));
  }

  // 2. Look up parent CoA
  const coa = await db
    .selectFrom("ChartOfAccounts")
    .selectAll()
    .where("id", "=", account.chartOfAccountsId)
    .executeTakeFirst();

  // 3. CoA must be ACTIVE
  if (!coa || coa.status === "ARCHIVED") {
    return err(new ChartOfAccountsArchivedError(account.chartOfAccountsId));
  }

  if (coa.status !== "ACTIVE") {
    return err(new ChartOfAccountsNotActiveError(account.chartOfAccountsId));
  }

  // 4. Account must be in expected from status
  if (!from.includes(account.status)) {
    return err(new InvalidStateTransitionError(id));
  }

  // 5. Update status to ACTIVE and clear successor
  const updated = await db
    .updateTable("Account")
    .set({
      status: "ACTIVE",
      successorAccountId: null,
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ account: updated! });
}
