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

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

export function createProfitCenterHierarchyNodeType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProfitCenterHierarchyNodeTypeParams<F>) {
  return db
    .type("ProfitCenterHierarchyNode", {
      name: db.string().description("Name of the hierarchy node"),
      hierarchyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.profitCenterHierarchyType ?? profitCenterHierarchy },
          backward: "nodes",
        })
        .description("Foreign key to ProfitCenterHierarchy"),
      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 profitCenterHierarchyNode = createProfitCenterHierarchyNodeType({});
