import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { costCenterHierarchy } from "./costCenterHierarchy";

export interface CreateCostCenterHierarchyNodeTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: F;
  costCenterHierarchyType?: TailorAnyDBType;
}

export function createCostCenterHierarchyNodeType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateCostCenterHierarchyNodeTypeParams<F>,
) {
  return db
    .type("CostCenterHierarchyNode", {
      name: db.string().description("Name of the hierarchy node"),
      hierarchyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costCenterHierarchyType ?? costCenterHierarchy },
          backward: "nodes",
        })
        .description("Foreign key to CostCenterHierarchy"),
      parentNodeId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "childNodes",
        })
        .description("Optional self-referencing foreign key to parent node"),
      sortOrder: db.int().description("Sort order within the hierarchy level"),
      level: db.int().description("Depth level in the hierarchy"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const costCenterHierarchyNode = createCostCenterHierarchyNodeType({});
