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

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

/**
 * Function: activateAccount
 *
 * Transitions a GL account from DRAFT to ACTIVE status, making it eligible
 * to receive journal postings from downstream modules.
 */
export async function run(db: Transaction, input: ActivateAccountInput, _ctx: CommandContext) {
  const { id, from = ["DRAFT"] } = 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?.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
  const updated = await db
    .updateTable("Account")
    .set({
      status: "ACTIVE",
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

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