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

export interface DeactivateAccountInput {
  id: string;
  successorAccountId?: string;
  preDeactivationHook?: (accountId: string) => Promise<boolean>;
}

/**
 * Function: deactivateAccount
 *
 * Transitions a GL account from ACTIVE to INACTIVE status, preventing new
 * journal postings while preserving history. An optional successor account
 * can be designated during deactivation.
 */
export async function run(db: Transaction, input: DeactivateAccountInput, _ctx: CommandContext) {
  const { id, successorAccountId, preDeactivationHook } = 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 (ARCHIVED is rejected)
  if (!coa || coa.status === "ARCHIVED") {
    return err(new ChartOfAccountsArchivedError(account.chartOfAccountsId));
  }

  // 4. Account must be ACTIVE
  if (account.status !== "ACTIVE") {
    return err(new InvalidStateTransitionError(id));
  }

  // 5. Pre-deactivation hook (GL balance check)
  if (preDeactivationHook) {
    const canDeactivate = await preDeactivationHook(id);
    if (!canDeactivate) {
      return err(new OpenBalancesExistError(id));
    }
  }

  // 6. Validate successor if provided
  if (successorAccountId) {
    const successor = await db
      .selectFrom("Account")
      .selectAll()
      .where("id", "=", successorAccountId)
      .executeTakeFirst();

    if (successor?.status !== "ACTIVE") {
      return err(new SuccessorNotActiveError(successorAccountId));
    }
  }

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

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