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

export interface GetProfitCenterInput {
  id: string;
}

/**
 * Function: getProfitCenter
 *
 * Retrieves a single profit center by id, including its hierarchy node assignments.
 */
export async function run(db: ReadonlyDB<DB>, input: GetProfitCenterInput) {
  const result = await db
    .selectFrom("ProfitCenter")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!result) {
    return ok({ profitCenter: null, hierarchyAssignments: [] });
  }

  const assignments = await db
    .selectFrom("ProfitCenterHierarchyAssignment")
    .selectAll()
    .where("profitCenterId", "=", input.id)
    .execute();

  return ok({ profitCenter: result, hierarchyAssignments: assignments });
}
