import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import { accountLifecycle } from "../db/account.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { AccountNotFoundError, InvalidStateTransitionError } from "../lib/errors.generated";

export interface ReactivateAccountInput {
  id: string;
}

/**
 * Function: reactivateAccount
 *
 * Transitions a GL account from INACTIVE back to ACTIVE status, making it
 * eligible to receive journal postings again.
 */
export async function run(db: Transaction, input: ReactivateAccountInput, _ctx: CommandContext) {
  const { id } = 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));
  }

  const nextStatus = accountLifecycle.tryTransition(account.status, "reactivate");
  if (!nextStatus) {
    return err(new InvalidStateTransitionError(id));
  }

  // 3. Update status
  const updated = await db
    .updateTable("Account")
    .set({ status: nextStatus })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ account: updated });
}
