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

export interface GetCostCenterInput {
  id: string;
}

/**
 * Function: getCostCenter
 *
 * Retrieves a single cost center by id, including the hierarchy node assignment.
 */
export async function run(db: ReadonlyDB<DB>, input: GetCostCenterInput) {
  const result = await db
    .selectFrom("CostCenter")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!result) {
    return ok({ costCenter: null });
  }

  const hierarchyNode = result.hierarchyNodeId
    ? ((await db
        .selectFrom("CostCenterHierarchyNode")
        .selectAll()
        .where("id", "=", result.hierarchyNodeId)
        .executeTakeFirst()) ?? null)
    : null;

  return ok({ costCenter: result, hierarchyNode });
}
