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

export interface GetCostCenterHierarchyInput {
  id: string;
}

async function loadNodesWithCostCenters(db: ReadonlyDB<DB>, hierarchyId: string) {
  const nodes = await db
    .selectFrom("CostCenterHierarchyNode")
    .selectAll()
    .where("hierarchyId", "=", hierarchyId)
    .orderBy("level", "asc")
    .orderBy("sortOrder", "asc")
    .execute();

  return Promise.all(
    nodes.map(async (node) => {
      const costCenters = await db
        .selectFrom("CostCenter")
        .selectAll()
        .where("hierarchyNodeId", "=", node.id)
        .execute();
      return { ...node, costCenters };
    }),
  );
}

/**
 * Function: getCostCenterHierarchy
 *
 * Retrieves a single cost center hierarchy by id, along with its hierarchy nodes
 * and the cost centers assigned to each node.
 */
export async function run(db: ReadonlyDB<DB>, input: GetCostCenterHierarchyInput) {
  const hierarchy = await db
    .selectFrom("CostCenterHierarchy")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!hierarchy) {
    return ok({ costCenterHierarchy: null, nodes: [] });
  }

  const nodesWithCostCenters = await loadNodesWithCostCenters(db, input.id);
  const nodes = buildTree(nodesWithCostCenters);

  return ok({ costCenterHierarchy: hierarchy, nodes });
}
