import type { ChartOfAccountsStatus } from "../generated/enums";
import type { DB } from "../generated/kysely-tailordb";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export type GetChartOfAccountsInput = { id: string } | { companyId: string; status?: string };

/**
 * Function: getChartOfAccounts
 *
 * Retrieves a single Chart of Accounts by id or by companyId (optionally filtered by status).
 */
export async function run(db: ReadonlyDB<DB>, input: GetChartOfAccountsInput) {
  let query = db.selectFrom("ChartOfAccounts").selectAll();

  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else if ("status" in input && input.status) {
    query = query
      .where("companyId", "=", input.companyId)
      .where("status", "=", input.status as ChartOfAccountsStatus);
  } else {
    query = query.where("companyId", "=", input.companyId).orderBy("createdAt", "desc");
  }

  const chartOfAccounts = await query.executeTakeFirst();

  return ok({ chartOfAccounts: chartOfAccounts ?? null });
}
